I'm rewriting some of my code to use Pipeable Operators in place of "patch" operators and I'm a little confused about when to use pipe()
and how do I subscribe to a piped Observable
to "activate" it if I only want side-effects?
For example, I have this code:
this.messages$ = this.messageService.getMessages(messageType)
.do((messages: Message[]) => {
console.log('The first message is ' + deviceMessages[0].text);
});
I get confused here because I figure I want to do this.messageService.getMessages(messageType).pipe(...)
so I get an Observable
returned and assigned to this.messages$
but then that won't execute because I haven't subscribe()
'd. But if I do .pipe(...).subscribe()
then it'll return a Subscription
object, which isn't what I want.
What should I be doing here?
Well, do it simply like this:
this.messages$ = this.messageService.getMessages(messageType).pipe(
tap((messages: Message[]) => {
console.log('The first message is ' + deviceMessages[0].text);
})
);
this.messages$.subscribe();
the tap operator is the equivalent of .do()
in rxjs 5 and above.