Junior — Middle
Explain the functioning mechanism of the flatMap operator in RxJava and how it processes data streams.
sobes.tech AI
Answer from AI
The flatMap operator in RxJava is used to transform each item emitted by the source Observable into a new Observable, and then merge all these inner Observables into a single stream, "flattening" their emissions.
How it works:
- For each item in the source stream, a function is called that returns a new Observable.
- All these new Observables are subscribed to, and their items are emitted into the resulting stream.
- Items from different inner Observables can arrive asynchronously and interleave.
This is useful when you need to perform asynchronous operations for each item and combine the results into a single stream.
Example:
Observable.just(1, 2, 3)
.flatMap(i -> Observable.just(i * 10, i * 20))
.subscribe(System.out::println);
The output will contain 10, 20, 20, 40, 30, 60 (the order may vary due to asynchrony).
Thus, flatMap allows working with nested streams and merging them into one, maintaining asynchrony and parallelism.