When do you use map vs flatMap in RxJava?

 Learning RxJava is an overwhelming exercise because it is a paradigm shift in the way you solve your coding problems. During this learning process, of the many doubts you'll have, one such would be, "When do you use map vs flatMap in RxJava?".

ProTip : Get used to understanding the Marble Diagram for understanding the basic concepts of Reactive Extensions.

Here is a simple thumb-rule that I use help me decide as when to use flatMap() over map() in Rx's Observable.

Once you come to a decision that you're going to employ a map transformation, you'd write your transformation code to return some Object right? If what you're returning as end result of your transformation is:
  • a non-observable object then you'd use just map(). And map() wraps that object in an Observable and emits it.
  • an Observable object, then you'd use flatMap(). And flatMap() unwraps the Observable, picks the returned object, wraps it with its own Observable and emits it.

Say for example we've a method titleCase(String inputParam) that returns Titled Cased String object of the input param. The return type of this method can be String or Observable<String>.
  • If the return type of titleCase(..) were to be mere String, then you'd use map(s -> titleCase(s))
  • If the return type of titleCase(..) were to be Observable<String>, then you'd use flatMap(s -> titleCase(s))

Hope that clarifies. And if this post helped you pick the concept, I'd appreciate you share the post and upvote this answer in StackOverflow. Thanks in advance :)