Observables rxjs recipes

Unsubscribing to observable in Angular

Create a timer with observable

Create a timer that will emit a value every 5000ms.

const timer = Rx.Observable.interval(5000);

js bin example of 2 sources (2 intervals emitters) with the second slowerarrow-up-right

[Observable] Observable.combineLatest

  • When to use? : You have 2 queries or more. You need to do something depending on of the results of those queries. For example, you need to wait for page params and get the connected user information...

CombineLatest emits an item whenever any of the source Observables emits an item (so long as each of the source Observables has emitted at least one item)

So you have 2 or more async observables, the Observable.combineLatest is called after each emitted their first value, and give the opportunity to a function to remit a item with the value of the last emitted item

[Subject] Behavior subject

A variable that is changed using next() and "watched" using subscribe

[Operator] map

import 'rxjs/add/operator/map';

Allow to change the value of each emitted items before it is sent to function subscribing to it.

[Operator] flatmap

Mind that in JS the name is not flatmap ! Look at flatmap official docarrow-up-rightflatmap.html

[Operator] do

import 'rxjs/add/operator/do';

Learn RXJS doc on doarrow-up-right

  • When to use? : To perform an action like logging that do not transform the observable result

[Operator] catch

import 'rxjs/add/operator/catch';

Learn RXJS doc on catcharrow-up-right

  • When to use? : to catch error, return an observable with the error information

[Operator] take

import 'rxjs/add/operator/take';

[Filter] filter

  • When to use? : Select the condition to receive a given observable, for example you want to make an API call only if the parameters are available

Learn RXJS on filterarrow-up-right

[Operator] withLatestFrom

import 'rxjs/add/operator/withLatestFrom';

  • When to use? Combine 2 sources with the latest emitted version for the second source. withLatestFrom is generally followed by a map where the 2 sources results .map([source1, source2) => { //handle 2 sources } can be manipulated

Learn RXJS doc on withlatestfromarrow-up-right

[Operator] exhaustMap

[Function] pipe method

https://blog.hackages.io/rxjs-5-5-piping-all-the-things-9d469d1b3f44arrow-up-right

Pipe method is available from Rxjs 5.5

Return an observable when another observable emit a value

Last updated