sanjihan
sanjihan

Reputation: 6046

startWith() that returns Subject

I want to emit values using Subject with default value.

startWith("def") is the method for this.

subject = new Rx.Subject().startWith("def value"); 

unfortunately startWIth returns Observable and therefore I cannot use onNext(), which is the sole reason I am using Subject in the first place. What is the workaround for this problem?

subject.onNext("next val"); //cannot call onNext, it is not a function of Observable

Upvotes: 1

Views: 2670

Answers (2)

Brandon
Brandon

Reputation: 39222

Your question isn't entirely clear. If you want all observers to see "def value" before anything else, then use @Pace's answer.

But if you want all observers to start with "the most recently emitted value", and use "def value" if they subscribe before you emit the first value, then use a BehaviorSubject:

var subject = new BehaviorSubject("default val");
subject.subscribe(...); // sees "default val", then anything you emit.

subject.next("foo");
subject.subscribe(...); // sees "foo", then anything else you emit (does not see "default val")

Upvotes: 3

Pace
Pace

Reputation: 43937

Just keep track of both the observable and the subject. I usually do something like...

export class FooService {

  private _foos: Subject<Foo> = new subject<Foo>();

  public get foos: Observable<Foo> {
    return this._foos.startsWith(...);
  }

  public emitFoo(foo: Foo) {
    this._foos.next(foo);
  }

}

Upvotes: 5

Related Questions