Use case of Observable .do() operator (rxjs)

soywod picture soywod · Dec 4, 2016 · Viewed 29.6k times · Source

 Context :

I'm building an angular 2 app (with a Firebase API). I'm using the AngularFire module. I was wondering how I can mix the canActivate method with the AngularFire auth Observable, and I found this post. The answer is to make the canActivate method returns an Observable<boolean> :

canActivate(): Observable<boolean> {
  return this.auth
    .take(1)
    .map((authState: FirebaseAuthState) => !!authState)
    .do(authenticated => {
      if (!authenticated) this.router.navigate(['/login']);
    });
}

It's the first time I see the Observable do operator, and I can't understand what it really does ? The official doc didnt help me, and I didn't found decent examples.

Question:

Can someone bring here some examples of .do() usage ? And difference with .subscribe() ?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Dec 4, 2016

Update

Now it's pipe( tap(...), ) instead of do()

Original

.do() is to execute code for each event. A difference to .map() is, that the return value of .do() is ignored and doesn't change what value the subscriber receives.