[java] When do you use map vs flatMap in RxJava?

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.