After some time we receive response for Madrid followed by London which are later received by subscriber. 7556900 (population of London) and 3255944 (Madrid) come first After a while Paris and Warsaw arrive as well. On one hand it's good that we can proceed with each population immediately when it arrives. This makes the system seem like more responsive. But we lost something. The input stream was "Warsaw", "Paris", "London", "Madrid" whereas the resulting stream contains population of "London", "Madrid", "Paris", "Warsaw". How can we tell which number represents which city?

Obviously the following solution is plain wrong, yet it's not unheard of in real code bases:

We combine cities with some random permutation of their population's. To make matters worse I managed to get wrong results after maybe dozen attempts. For some reason this program was working on my machine most of the time. Worst kind of bug you can imagine.

The problem with flatMap() is that it looses the original request. Imagine an asynchronous system where you receive a response on some sort of queue but have no idea what the request was. An obvious solution is to somehow attach some sort of correlation ID or even the whole request to the response. Unfortunately populationOf(String city) doesn't return the original request (city), only response (population). It would be so much easier if it returned something like CityWithPopulation value object or even Pair<String, Long>. So now imagine we are enhancing the original method by attaching the request (city):

I found flatMap() with nested map() adding additional context to be the most effective way of dealing with out-of-order results. Surely it's not the most readable piece of reactive code so make sure you hide this complexity behind some facade.

UPDATE

As noted by Dávid Karnok in his comment to this post, the map() operator inside flatMap() is such a common idiom that a specialized flatMap() overload exists. Apart from standard transformation function (in our case String -> Flowable<Long>) it also takes combiner bi-function (e.g. (String, Long) -> SomeType). The purpose of this function is to provide a transformation that combines input item with each output item generated by transformation. This is precisely what we did with nested map() (enriching population with the name of city it corresponds to), but much shorter:

really nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blogs. Aws Training in BTM Layout