Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs: Merge two streams with one stream that depends of another

I have a stream that calls a service that returns a stream that needs the info of the original stream for the request.

this.messages$ = this.selectedChat$
.switchMap(chat => this.chatService.subscribeMessages(chat.room))
.map(messages) =>
  messages.map((message: any) => {
    //Here need add information of the chat object
    return message;
  })
);

All operators that I see that can merge the streams and separate them later (like combineLatest) receive parameters, therefore, I can´t use the original stream info to call the service that generates the other stream, and I would not like to use subscribe on the original stream and return a new stream inside the subscribe because it's a little messy code.

Any advice?

like image 905
Daniel Caldera Avatar asked Nov 06 '17 16:11

Daniel Caldera


1 Answers

Use the selector function in the switchMap operation:

this.messages$ = this.selectedChat$
.switchMap(chat => this.chatService.subscribeMessages(chat.room), 
(chat,messages)=>({chat,messages})) // create a new object, using the inner observable and the mapped one
.map(data =>
  data.messages.map((message: any) => {
    // Here data.chat has the chat information
    return message;
  })
);

For more information about the switchMap operator check here

like image 64
Jota.Toledo Avatar answered Sep 22 '22 21:09

Jota.Toledo