10

I am pretty new to Observables. How would I create Observable just from a simple string? Then subscribe to it and output it when it changes.

Does that make sense?

I don't have any luck with google search. Probably wrong keywords?


Adding some code for better explanation:

My constructor on service

constructor() {
  // Create observable stream to output our data
  this.notice = Observable.create(
    (observer) => this.observer = observer;
  );
};

My method on service

set(string) {
  this.notice.subscribe((value) => {
    // Push the new value into the observable stream
    this.observer.next(string);
  }, (error) => console.log('Could not set data.'));
}

Calling service method 

setNotice(event) {
  event.preventDefault();

  // Calling service to set notice
  this.noticeService.set('This is a string');
}

I think I am doing something wrong here? But not sure how to ask. I would be grateful for any of the explanations.

be-codified
  • 4,954
  • 17
  • 39
  • 65
  • Waht about this.notice.unsubscribe() in ngDestroy() too? I know that's a common cause of memory leaks for manually added event listeners... So I presume this would be the same. – JGFMK Aug 11 '17 at 18:55
  • 1
    I'd also be considering BehaviorSubject too for this. https://stackoverflow.com/questions/39494058/behaviorsubject-vs-observable – JGFMK Aug 11 '17 at 18:57

1 Answers1

19

You can use the of method of the Observable class:

var obs = Observable.of('some string');

Edit

Regarding the code of your service, I would refactor the code of your set method like this:

set(string) {
  this.observer.next(string);
}

You can subscribe on the notice property in another part of your application to be notified.

Saksham
  • 8,705
  • 6
  • 42
  • 67
Thierry Templier
  • 191,422
  • 38
  • 386
  • 349
  • thank you for showing this. I am wondering how to make 'some string' as a value of variable that could change. How to push it inside Observable then? – be-codified Feb 22 '16 at 15:07
  • In fact, you can't. That said you can fire event when the value changes. For this you need to create a raw observable: `Observable.create((observer) => { observer.next('some string'); });`. The `next` method can be called several times... Note that you can set the `observer` variable into a variable outside the callback. – Thierry Templier Feb 22 '16 at 15:12
  • 1
    You're welcome! I think the problem is at the level of your `set` method. I updated my answer... – Thierry Templier Feb 22 '16 at 16:09
  • 1
    I would create the observable without the word observable `var obs = of('some string');` – Mike Poole Apr 01 '20 at 08:59