What is the difference between map() and switchMap() methods?

Igor Bubelov picture Igor Bubelov · Nov 30, 2017 · Viewed 22.8k times · Source

What is the difference between those 2 methods of the LiveData class? The official doc and tutorial are pretty vague on that. In the map() method the first parameter called source but in the switchMap() it called trigger. What's the rationale behind that?

Answer

Rupesh picture Rupesh · Dec 7, 2017

As per the documentation

Transformations.map()

Applies a function on the value stored in the LiveData object, and propagates the result downstream.

Transformations.switchMap()

Similar to map, applies a function to the value stored in the LiveData object and unwraps and dispatches the result downstream. The function passed to switchMap() must return a LiveData object.

In other words, I may not be 100% correct but if you are familiar with RxJava; Transformations#map is kind of similar to Observable#map & Transformations#switchMap is similar to Observable#flatMap.

Let's take an example, there is a LiveData which emits a string and we want to display that string in capital letters.

One approach would be as follows; in an activity or fragment

Transformations.map(stringsLiveData, String::toUpperCase)
    .observe(this, textView::setText);

the function passed to the map returns a string only, but it's the Transformation#map which ultimately returns a LiveData.

The second approach; in an activity or fragment

Transformations.switchMap(stringsLiveData, this::getUpperCaseStringLiveData)
            .observe(this, textView::setText);

private LiveData<String> getUpperCaseStringLiveData(String str) {
    MutableLiveData<String> liveData = new MutableLiveData<>();
    liveData.setValue(str.toUpperCase());
    return liveData;
}

If you see Transformations#switchMap has actually switched the LiveData. So, again as per the documentation The function passed to switchMap() must return a LiveData object.

So, in case of map it is the source LiveData you are transforming and in case of switchMap the passed LiveData will act as a trigger on which it will switch to another LiveData after unwrapping and dispatching the result downstream.