Ka Mok
Ka Mok

Reputation: 1988

RXJS Subject, return the same value on every first subscribe

I know I need to use startWith, but still trying to figure out how to use it. If I just do Subject.create().startWith("Some Value), it turns the Subject into a Observable, and I can't use next to emit.

So multiple subscribers should be able subscribe to it. Should be able to call next on the Subject. Going through the docs of Subject.create(), but it's going slow.

Edit: I got it to work after using the accepted solution. The reason why it wasn't working before was because I put the .next call inside the subscription.

Eg:

observable.subscribe((res) => {
// do something
s.next('another res');
}

This creates an infinite loop, and I think RXJS prevented it? Anyway, I put the next in there for debug purposes. I moved it outside of that subscribe block and now and initial result emits, then when next is called, whatever was inside subscribe emit again.

Upvotes: 1

Views: 1093

Answers (1)

martin
martin

Reputation: 96899

You should avoid using Subject.create() and use just Subject(). See: Subject vs AnonymousSubject

Just keep a reference to the Subject instance and another reference to the Observable chain you need:

let s = new Subject();
let observable = s.startWith("Some initial message");

observable.subscribe(...);
s.next('whatever');

Upvotes: 1

Related Questions