January 11, 2019

#RxJava Part 5 : map() vs flatMap()

What is the difference between map() and flatMap()?
The map() method works well with Optional if the function returns the exact type we need. e.g:

Optional s = Optional.of("employee");

But in more complex cases we might be given a function that returns an Optional too. In such cases using map() would lead to a nested structure, as the map() implementation does an additional wrapping internally.

assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string") .map(s -> Optional.of("STRING")));

In the above example we end up with the nested structure Optional>. Although it works, it's pretty complicated to use and does not provide any additional null-safety, in such cases its better to keep a flat structure by using flatMap().

assertEquals(Optional.of("STRING"), Optional.of("string").flatMap(s -> Optional.of("STRING")));

In simple words, Map transforms the items emitted by an Observable by applying a function to each item. However, FlatMap transforms the items emitted by an Observable into Observables. FlatMap mapper returns an observable itself, so it is used to map over asynchronous operations.

-K Himaanshu Shuklaa..

No comments:

Post a Comment