How to get last value when subscribing to an Observable?

kdu picture kdu · May 12, 2016 · Viewed 24.8k times · Source

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?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · May 12, 2016

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.