Search code examples
rxjsobservablesubject-observer

RXJS Observable - How to call next from outside of the Observable's constructor


I am building a service which exposes an Observable. In this service I receive external function calls which should trigger a next call on the Observable so that various consumers get the subscribe event. During Observer constructor I can call next and everything works great, but how can I access this outside of the constructor so that external triggers can fire next calls?

private myObservable$: Observable<any>;

During service init I do

this.myObservable$ = new Observable(observer => {
    observer.next("initial message");
}

Then in other methods of the same service I want to be able to execute something like

this.myObservable$.observer.next("next message");

The above obviously doesn't work, but how can I accomplish this goal?

I'm assuming I'm missing something basic since there must be a way to emit further messages outside of the Observable's initial constructor


Solution

  • You should create a Subject for that

    this.myObservable$ = new Subject();
    

    And then you can call at any point:

    this.myObservable$.next(...);
    

    Or use subscribe:

    this.myObservable$.subscribe(...)