I'm in a case where I want to subscribe as soon as possible to two different obsevable, but wait for the first one to emit before the second one emits.
For instance I'm developing a chat application where I want to retrieve all previous messages stored on a DB, but also subscribe to a stream which emits new ones.
I want something like this:
readonly messages$ = this.service.getStoredMessages().pipe(
switchMapTo(this.service.getNewMessages())
)
The problem with this is that I may miss some messages because of a late subscription to getNewMessages()
. What I need to do is to subscribe as soon as possible to both observables, but the second one (getNewMessages()
) should emits only after getStoredMessages()
emits.
getStoredMessages
is a pull request that sends a snapshot of the "historical" messages. However, it's possible that other messages get created while the request is being served. I've been in that situation, and what I did was buffer the messages that were received before receiving the result of the historical data, and then "merge" the historical with the buffered messages (ensuring that there are no duplicates), then emit those and afterwords emit the new messages. I could be wrong, but I think what's the OP is looking for. – JosepcombineLatest
is going to help you for what you are trying to do here, but now that you've confirmed that this is what you are looking for I will share a way to solve this. Although, I'm genuinely curious to see if I'm missing something, andcombineLatest
can help here. – Josep