As my journey into the marvelous world of RxJS goes on, I want to share a bit of knowledge I’ve got following courses, blogs and so on regarding the concatenation strategies.
First off, what is a concatenation strategy?
As you may probably know, RxJS is about streams of values, often handled asynchronously, as HTTP calls can be, that’s why it can happen that we have to use some sort of concatenation to keep our code execution in order, let’s see how.
Let’s put that we have a text box where we freely type anything, and that at each input typed by the user, we are sending 3 HTTP requests to a server, combining the letter typed with the numbers 1,2 and 3, and so on with every letter typed. In other words, if the user types “A”, the client will send three requests like:
[GET] /endpoint/A1
[GET] /endpoint/A2
[GET] /endpoint/A3
FIRST STRATEGY: concatMap
Given a stream of value (the user that types n times), the concatMap operator waits for each operation before initializing the next one.
Given our example above, the marble diagram here shows the first stream of values (A, B and C) which represent the values emitted by the user, and the stream 1,2 and 3 which represent our merge (“A1” , “A2” and so on).
Let’s follow step by step:
The user types A, and the value first merged value is emitted as a [GET]/endpoint/A1 , when the request is resolved then…
…the client starts [GET]/endpoint/A2 , when resolved then…
… the client starts [GET]/endpoint/A3, when resolved then…
…User types B, then…
[GET]/endpoint/B1 starts, and once resolved…
…[GET]/endpoint/B2 starts but…
…In the meantime the user types C, but our concatMap enqueues C1, C2, and C3 after B3 emission, so…
… [GET]/endpoint/B3 starts, and once resolved…
… [GET]/endpoint/C1 starts, and once resolved…
… [GET]/endpoint/C2 starts, and once resolved…
… [GET]/endpoint/C3 starts
Now even displacing B much much before the result won’t change, as you can se in this edited marble diagram below.
I hope that this concatenation strategy is a bit clearer :)
Top comments (0)