51

I am using Transformations.switchMap in my ViewModel so my LiveData collection, observed in my fragment, reacts on changes of code parameter.

This works perfectly :

public class MyViewModel extends AndroidViewModel {

    private final LiveData<DayPrices> dayPrices;
    private final MutableLiveData<String> code = new MutableLiveData<>();
    // private final MutableLiveData<Integer> nbDays = new MutableLiveData<>();
    private final DBManager dbManager;

    public MyViewModel(Application application) {
        super(application);
        dbManager = new DBManager(application.getApplicationContext());
        dayPrices = Transformations.switchMap(
            code,
            value -> dbManager.getDayPriceData(value/*, nbDays*/)
        );
    }

    public LiveData<DayPrices> getDayPrices() {
        return dayPrices;
    }

    public void setCode(String code) {
        this.code.setValue(code);
    }

    /*public void setNbDays(int nbDays) {
        this.nbDays.setValue(nbDays);
    }*/

}

public class MyFragment extends Fragment {

    private MyViewModel myViewModel;

    myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
    myViewModel.setCode("SO");
    //myViewModel.setNbDays(30);
    myViewModel.getDayPrices().observe(MyFragment.this, dataList -> {
        // update UI with data from dataList
    });
}

Problem

I now need another parameter (nbDays commented in the code above), so that my LiveData object reacts on both parameters change (code and nbDays).

How can I chain transformations ?

Some reading pointed me to MediatorLiveData, but it does not solve my problem (still need to call single DB function with 2 parameters, I don't need to merge 2 liveDatas).

So I tried this instead of switchMap but code and nbDays are always null.

dayPrices.addSource(
    dbManager.getDayPriceData(code.getValue(), nbDays.getValue),
    apiResponse -> dayPrices.setValue(apiResponse)
);

One solution would be to pass an object as single parameter by I'm pretty sure there is a simple solution to this.

5 Answers 5

70

Source : https://plus.google.com/+MichielPijnackerHordijk/posts/QGXF9gRomVi

To have multiple triggers for switchMap(), you need to use a custom MediatorLiveData to observe the combination of the LiveData objects -

class CustomLiveData extends MediatorLiveData<Pair<String, Integer>> {
    public CustomLiveData(LiveData<String> code, LiveData<Integer> nbDays) {
        addSource(code, new Observer<String>() {
            public void onChanged(@Nullable String first) {
                setValue(Pair.create(first, nbDays.getValue()));
            }
        });
        addSource(nbDays, new Observer<Integer>() {
            public void onChanged(@Nullable Integer second) {
                setValue(Pair.create(code.getValue(), second));
            }
        });
    }
}

Then you can do this -

CustomLiveData trigger = new CustomLiveData(code, nbDays);
LiveData<DayPrices> dayPrices = Transformations.switchMap(trigger, 
    value -> dbManager.getDayPriceData(value.first, value.second));

If you use Kotlin and want to work with generics:

class DoubleTrigger<A, B>(a: LiveData<A>, b: LiveData<B>) : MediatorLiveData<Pair<A?, B?>>() {
    init {
        addSource(a) { value = it to b.value }
        addSource(b) { value = a.value to it }
    }
}

Then:

val dayPrices = Transformations.switchMap(DoubleTrigger(code, nbDays)) {
    dbManager.getDayPriceData(it.first, it.second)
}
2
  • Thanks, very helpful! But in this case switchMap is init two times in a row, is it possible to skip 1st source in this case? Apr 12, 2019 at 9:06
  • @aleksandrbel Do you mean that switchMap can be triggered twice using separate setters for code and nbDays? Then yeah, that can cause the observer to receive two back-to-back values. If you don't want that behaviour, it would be better to use only a single Pair object in the MutableLiveData that combines both values like in the answer by OP below.
    – jL4
    Aug 13, 2019 at 9:56
24

Custom MediatorLiveData as proposed by @jL4 works great and is probably the solution.

I just wanted to share the simplest solution that I think is to use an inner class to represent the composed filter values :

public class MyViewModel extends AndroidViewModel {

    private final LiveData<DayPrices> dayPrices;
    private final DBManager dbManager;
    private final MutableLiveData<DayPriceFilter> dayPriceFilter;

    public MyViewModel(Application application) {
        super(application);
        dbManager = new DBManager(application.getApplicationContext());
        dayPriceFilter = new MutableLiveData<>();
        dayPrices = Transformations.switchMap(dayPriceFilter, input -> dbManager.getDayPriceData(input.code, input.nbDays));
    }

    public LiveData<DayPrices> getDayPrices() {
        return dayPrices;
    }

    public void setDayPriceFilter(String code, int nbDays) {
        DayPriceFilter update = new DayPriceFilter(code, nbDays);
        if (Objects.equals(dayPriceFilter.getValue(), update)) {
            return;
        }
        dayPriceFilter.setValue(update);
    }

    static class DayPriceFilter {
        final String code;
        final int nbDays;

        DayPriceFilter(String code, int nbDays) {
            this.code = code == null ? null : code.trim();
            this.nbDays = nbDays;
        }
    }

}

Then in the activity/fragment :

public class MyFragment extends Fragment {

    private MyViewModel myViewModel;

    myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
    myViewModel.setDayPriceFilter("SO", 365);
    myViewModel.getDayPrices().observe(MyFragment.this, dataList -> {
        // update UI with data from dataList
    });
}
1
  • 1
    You may want to implement "equals" in DayPriceFilter.
    – æ-ra-code
    Jan 8, 2021 at 15:41
22

A simplification of jL4's answer, (and also in Kotlin in case it helps anybody)... no need to create a custom class for this:

class YourViewModel: ViewModel() {

    val firstLiveData: LiveData<String> // or whatever type
    val secondLiveData: LiveData<Int> // or whatever

    // the Pair values are nullable as getting "liveData.value" can be null
    val combinedValues = MediatorLiveData<Pair<String?, Int?>>().apply {
        addSource(firstLiveData) { 
           value = Pair(it, secondLiveData.value)
        }
        addSource(secondLiveData) { 
           value = Pair(firstLiveData.value, it)
        }
    }

    val results = Transformations.switchMap(combinedValues) { pair ->
      val firstValue = pair.first
      val secondValue = pair.second
      if (firstValue != null && secondValue != null) {
         yourDataSource.yourLiveDataCall(firstValue, secondValue)
      } else null
    }

}

Explanation

Any update in firstLiveData or secondLiveData will update the value of combinedValues, and emit the two values as a pair (thanks to jL4 for this).

Calling liveData.value can be null, so this solution makes the values in Pair nullable to avoid Null Pointer Exception.

So for the actual results/datasource call, the switch map is on the combinedValues live data, and the 2 values are extracted from the Pair and null checks are performed, so you can be sure of passing non-null values to your data source.

1
  • Thats a very nice solution. Is there anyway to extend it with N sources?? I have a case that the sources number is unknown..!
    – james04
    Sep 16, 2020 at 13:32
1

I use following classes to transform many live data with different types

class MultiMapLiveData<T>(
    private val liveDataSources: Array<LiveData<*>>,
    private val waitFirstValues: Boolean = true,
    private val transform: (signalledLiveData: LiveData<*>) -> T
): LiveData<T>() {
    private val mObservers = ArrayList<Observer<Any>>()
    private var mInitializedSources = mutableSetOf<LiveData<*>>()

    override fun onActive() {
        super.onActive()

        if (mObservers.isNotEmpty()) throw InternalError(REACTIVATION_ERROR_MESSAGE)
        if (mInitializedSources.isNotEmpty()) throw InternalError(REACTIVATION_ERROR_MESSAGE)

        for (t in liveDataSources.indices) {
            val liveDataSource = liveDataSources[t]
            val observer = Observer<Any> {
                if (waitFirstValues) {
                    if (mInitializedSources.size < liveDataSources.size) {
                        mInitializedSources.add(liveDataSource)
                    }
                    if (mInitializedSources.size == liveDataSources.size) {
                        value = transform(liveDataSource)
                    }
                } else {
                    value = transform(liveDataSource)
                }
            }
            liveDataSource.observeForever(observer)
            mObservers.add(observer)
        }
    }

    override fun onInactive() {
        super.onInactive()
        for (t in liveDataSources.indices) {
            val liveDataSource = liveDataSources[t]
            val observer = mObservers[t]
            liveDataSource.removeObserver(observer)
        }
        mObservers.clear()
        mInitializedSources.clear()
    }

    companion object {
        private const val REACTIVATION_ERROR_MESSAGE = "Reactivation of active LiveData"
    }
}


class MyTransformations {
    companion object {
        fun <T> multiMap(
            liveDataSources: Array<LiveData<*>>,
            waitFirstValues: Boolean = true,
            transform: (signalledLiveData: LiveData<*>) -> T
        ): LiveData<T> {
            return MultiMapLiveData(liveDataSources, waitFirstValues, transform)
        }

        fun <T> multiSwitch(
            liveDataSources: Array<LiveData<*>>,
            waitFirstValues: Boolean = true,
            transform: (signalledLiveData: LiveData<*>) -> LiveData<T>
        ): LiveData<T> {
            return Transformations.switchMap(
                multiMap(liveDataSources, waitFirstValues) {
                    transform(it)
                }) {
                    it
                }
        }
    }
}

Usage: Note that the logic of the work is slightly different. The LiveData that caused the update (signalledLiveData) is passed to the Tranformation Listener as parameter, NOT the values of all LiveData. You get the current LiveData values yourself in the usual way via value property.

examples:

class SequenceLiveData(
    scope: CoroutineScope,
    start: Int,
    step: Int,
    times: Int
): LiveData<Int>(start) {
    private var current = start
    init {
        scope.launch {
            repeat (times) {
                value = current
                current += step
                delay(1000)
            }
        }
    }
}



suspend fun testMultiMap(lifecycleOwner: LifecycleOwner, scope: CoroutineScope) {
    val liveS = MutableLiveData<String>("aaa")
    val liveI = MutableLiveData<Int>()
    val liveB = MutableLiveData<Boolean>()

    val multiLiveWait: LiveData<String> = MyTransformations.multiMap(arrayOf(liveS, liveI, liveB)) {
        when (it) {
            liveS -> log("liveS changed")
            liveI -> log("liveI changed")
            liveB -> log("liveB changed")
        }
        "multiLiveWait: S = ${liveS.value}, I = ${liveI.value}, B = ${liveB.value}"
    }

    val multiLiveNoWait: LiveData<String> = MyTransformations.multiMap(arrayOf(liveS, liveI, liveB), false) {
        when (it) {
            liveS -> log("liveS changed")
            liveI -> log("liveI changed")
            liveB -> log("liveB changed")
        }
        "multiLiveNoWait: S = ${liveS.value}, I = ${liveI.value}, B = ${liveB.value}"
    }

    multiLiveWait.observe(lifecycleOwner) {
        log(it)
    }

    multiLiveNoWait.observe(lifecycleOwner) {
        log(it)
    }

    scope.launch {
        delay(1000)
        liveS.value = "bbb"
        delay(1000)
        liveI.value = 2222
        delay(1000)
        liveB.value = true          // ***
        delay(1000)
        liveI.value = 3333


        //  multiLiveWait generates:
        //
        //           <-- waits until all sources get first values (***)
        //
        //      liveB changed: S = bbb, I = 2222, B = true
        //      liveI changed: S = bbb, I = 3333, B = true

        //  multiLiveNoWait generates:
        //      liveS changed: S = aaa, I = null, B = null
        //      liveS changed: S = bbb, I = null, B = null
        //      liveI changed: S = bbb, I = 2222, B = null
        //      liveB changed: S = bbb, I = 2222, B = true      <-- ***
        //      liveI changed: S = bbb, I = 3333, B = true

    }
}

suspend fun testMultiMapSwitch(lifecycleOwner: LifecycleOwner, scope: CoroutineScope) {
    scope.launch {
        val start1 = MutableLiveData(0)
        val step1 = MutableLiveData(1)
        val multiLiveData = MyTransformations.multiSwitch(arrayOf(start1, step1)) {
            SequenceLiveData(scope, start1.value!!, step1.value!!, 5)
        }

        multiLiveData.observe(lifecycleOwner) {
            log("$it")
        }
        delay(7000)

        start1.value = 100
        step1.value = 2
        delay(7000)

        start1.value = 200
        step1.value = 3
        delay(7000)


        // generates:
        //      0
        //      1
        //      2
        //      3
        //      4
        //      100     <-- start.value = 100
        //      100     <-- step.value = 2
        //      102
        //      104
        //      106
        //      108
        //      200     <-- start.value = 200
        //      200     <-- step.value = 3
        //      203
        //      206
        //      209
        //      212

    }
}
0

I faced a similar problem. There are 2 ways to solve this:

  1. Either use MediatorLiveData
  2. Use RxJava as it has various operators to do such kind of complex stuff

If you don't know RxJava, then I'd recommend writing your custom MediatorLiveData class. To learn how write custom MediatorLiveData class check out this example: https://gist.github.com/AkshayChordiya/a79bfcc422fd27d52b15cdafc55eac6b

6
  • How can i make a network call which require 4 LiveData (eg. userId, emial ,apiKey and so on ..).Transformation.switchMap accept only one LiveData paramPlease give some suggestion. Thz
    – amlwin
    Jul 29, 2018 at 6:01
  • I came across a similar situation and I used MediatorLiveData. I'd recommend about it and see if it fits your use-case else you could use RxJava and then convert it into LiveData. Jul 29, 2018 at 6:35
  • if you wouldn't mind, could you share me some code snippet?
    – amlwin
    Jul 30, 2018 at 2:37
  • 1
    @RichardLeMesurier It keeps becoming invalid because there are constant changes in the repository. Hence now I have added a link to my gist so it doesn't break Dec 11, 2018 at 11:14
  • 1
    Frustrating, yes. I also just posted an image link to an answer and I know that soon it too will become dead... Dec 11, 2018 at 15:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.