Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last value from a Subject?

I have two Angular2 components which need to share data via a service:

@Injectable() export class SearchService {   private searchResultSource = new Subject<string>()   searchResult$ = this.searchResultSource.asObservable()    setSearchResults(_searchResult: string): void {     this.searchResultSource.next(_searchResult)   } } 

Suppose ComponentA is rendered and it emits an event via SearchService.setSearchResults. Then the user navigates to ComponentB, which also subscribes to searchResult$. However, ComponentB will never observe the event emitted by ComponentA because it was not subscribed to searchResult$ at the time ComponentA emitted an event, as it did not exist.

How can I create an Observable which emits the last event to every new subscriber?

like image 945
kdu Avatar asked May 11 '16 22:05

kdu


People also ask

How do you find last emitted value from subject?

There are two ways to get this last emited value. You can either get the value by accessing the . value property on the BehaviorSubject or you can subscribe to it. If you subscribe to it, the BehaviorSubject will directly emit the current value to the subscriber.

How do you get the last emitted Observable?

Rather than a standard subject (Observable) that just emits values as they come in, a BehaviorSubject emits the last value upon subscribe() . You can also get the last value manually using the BehaviorSubjects getValue() method.

How do you find the current value of the subject RxJS?

To get current value of RxJS Subject or Observable, we can use the first method. const observable = of("foo"); const hasValue = (value: any) => { return value !== null && value !== undefined; }; const getValue = <T>(observable: Observable<T>): Promise<T> => { return observable.

How do you find the value of BehaviorSubject?

So the only solution that I found to get the value of a BehaviorSubject was: let value; myBehaviorSubject. take(1). subscribe( (e) => value = e );


2 Answers

BehaviorSubject immediately emits the last value to new subscribers:

@Injectable() export class SearchService {    private searchResultSource = new BehaviorSubject<string>('');    setSearchResults(_searchResult: string): void {       this.searchResultSource.next(_searchResult);   } } 

ReplaySubject emits all previous events to new subscribers.

like image 161
Günter Zöchbauer Avatar answered Sep 30 '22 20:09

Günter Zöchbauer


You can use the ReplaySubject to always get the last value of the Observer, something like this :

@Injectable() export class SearchService {    private searchResultSource = new ReplaySubject<string>(1);    setSearchResults(_searchResult: string): void {       this.searchResultSource.next(_searchResult);   } } 

And just subscribe as normal.
A more advanced example can be found here : caching results with angular2 http service

like image 26
tibbus Avatar answered Sep 30 '22 18:09

tibbus