Justin Degonda
Justin Degonda

Reputation: 103

RXJS Get Current Value of a ReplaySubject

I am trying to pull the current value from a ReplySubject on login. On subscribe in the current flow, the previous value is returned instead of a the current value. So the stuff received is the previous stuff at login and not the current stuff. Is there a way to get the current value of the observable on subscribe in the ReplaySubject without having to resort to a BehaviorSubject?

stuff.service.ts:

 private _stuffSubject = new ReplaySubject<any>();
 private _stuff$: Observable<any> = this._someSubject.asObservable();

  get stuff$ () {
   return this._stuff$;
  }

  private fetchStuff () {
    return this.http.get('/stuff/current')
      .map(data =>  {
        return data.json()
      })
      .catch(err => {
        console.debug(this.constructor.name, 'handled error ->', err.message);
        return Observable.of(false);
      })
      .map(stuff => {
        this._stuffSubject.next(stuff);
      })
  }

stuff.component.ts:

this.stuffService.stuff$
  .subscribe(({stuff1, stuff2, stuff3}) => {
    this.stuff1 = `${stuff1}`;
    this.stuff2 = `${stuff2}`;
    this.stuff3 = `${stuff3}`;
  });

Upvotes: 2

Views: 7516

Answers (1)

asmmahmud
asmmahmud

Reputation: 5044

You can set the buffer size to 1:

private _stuffSubject = new ReplaySubject<any>(1);

Upvotes: 3

Related Questions