clzola
clzola

Reputation: 2025

How to combine two live data one after the other?

I have next use case: User comes to registration form, enters name, email and password and clicks on register button. After that system needs to check if email is taken or not and based on that show error message or create new user...

I am trying to do that using Room, ViewModel and LiveData. This is some project that on which I try to learn these components and I do not have remote api, I will store everything in local database

So I have these classes:

So the idea that I have is that there will be listener attached to register button which will call RegisterViewModel::register() method.

class RegisterViewModel extends ViewModel {

    //...

    public void register() {
        validationErrorMessage.setValue(null);
        if(!validateInput())
            return;
        registrationService.performRegistration(name.get(), email.get(), password.get());
    }

    //...

}

So that is the basic idea, I also want for performRegistration to return to me newly created user.

The thing that bothers me the most is I do not know how to implement performRegistration function in the service

class UsersRegistrationService {
    private UsersRepository usersRepo;

    //...

    public LiveData<RegistrationResponse<Parent>>  performRegistration(String name, String email, String password) {
         // 1. check if email exists using repository
         // 2. if user exists return RegistrationResponse.error("Email is taken") 
         // 3. if user does not exists create new user and return RegistrationResponse(newUser)
    }
}

As I understand, methods that are in UsersRepository should return LiveData because UsersDAO is returning LiveData

@Dao
abstract class UsersDAO { 
    @Query("SELECT * FROM users WHERE email = :email LIMIT 1")
    abstract LiveData<User> getUserByEmail(String email);
}

class UsersRepository {
    //...
    public LiveData<User> findUserByEmail(String email) {
        return this.usersDAO.getUserByEmail(email);
    }
}

So my problem is how to implement performRegistration() function and how to pass value back to view model and then how to change activity from RegisterActivity to MainActivity...

Upvotes: 61

Views: 59995

Answers (14)

MikkelT
MikkelT

Reputation: 815

I get that having a combine method would be really convenient, but your intended functionality can easily be achieved in a more rustic way:

Define your liveData

    private val liveDataA = MutableLiveData<String>()
    private val liveDataB = MutableLiveData<String>()
    private val liveDataC = MutableLiveData<String>()

Define your onData method in the fragment/activity

private fun onData() {
    val dataA = viewModel.liveDataA.value ?: return
    val dataB = viewModel.liveDataB.value ?: return
    val dataC = viewModel.liveDataC.value ?: return
    // DoStuff with non-null values
}

Observe your livedatas

observe(viewModel.liveDataA) {
   onData()
}
observe(viewModel.liveDataB) {
   onData()
}
observe(viewModel.liveDataC) {
   onData()
}

It's clunky, yes, but it works

Upvotes: 0

Peter
Peter

Reputation: 403

Java version, if anyone else is stuck working on some old project

var fullNameLiveData = LiveDataCombiner.combine(
    nameLiveData,
    surnameLiveData,
    (name, surname) -> name + surname
)
public class LiveDataCombiner<First, Second, Combined> {

    private First first;
    private Second second;
    private final MediatorLiveData<Combined> combined = new MediatorLiveData<>();
    private final BiFunction<First, Second, Combined> combine;

    public LiveData<Combined> getCombined() {
        return combined;
    }

    public static <First, Second, Combined>LiveDataCombiner<First, Second, Combined> combine(
            LiveData<First> firstData,
            LiveData<Second> secondData,
            BiFunction<First, Second, Combined> combine
    ) {
        return new LiveDataCombiner<>(firstData, secondData, combine);
    }

    private LiveDataCombiner(
            LiveData<First> firstData,
            LiveData<Second> secondData,
            BiFunction<First, Second, Combined> combine
    ) {
        this.combine = combine;
        addSource(firstData, value -> first = value);
        addSource(secondData, value -> second = value);
    }

    private <T> void addSource(LiveData<T> source, Consumer<T> setValue) {
        combined.addSource(source, second -> {
            setValue.accept(second);
            emit(combine());
        });
    }

    private Combined combine() {
        return combine.apply(first, second);
    }

    private void emit(Combined value) {
        if (combined.getValue() != value)
            combined.setValue(value);
    }
}

Upvotes: 0

luigi23
luigi23

Reputation: 305

Solved with LiveData extensions

fun <T, R> LiveData<T>.map(action: (t: T) -> R): LiveData<R> =
    Transformations.map(this, action)

fun <T1, T2, R> LiveData<T1>.combine(
    liveData: LiveData<T2>,
    action: (t1: T1?, t2: T2?) -> R
): LiveData<R> =
    MediatorLiveData<Pair<T1?, T2?>>().also { med ->
        med.addSource(this) { med.value = it to med.value?.second }
        med.addSource(liveData) { med.value = med.value?.first to it }
    }.map { action(it.first, it.second) }

Upvotes: 1

M-Wajeeh
M-Wajeeh

Reputation: 17284

One approach is to use flows for this.

val profile = MutableLiveData<ProfileData>()
val user = MutableLiveData<CurrentUser>()

val titleFlow = profile.asFlow().combine(user.asFlow()){ profile, user ->
    "${profile.job} ${user.name}"
}

And then your Fragment/Activity:

viewLifecycleOwner.lifecycleScope.launch { 
    viewModel.titleFlow.collectLatest { title ->
        Log.d(">>", title)
    }
}

One advantage to this approach is that titleFlow will only emit value when both live datas have emitted at least one value. This interactive diagram will help you understand this https://rxmarbles.com/#combineLatest

Alternative syntax:

val titleFlow = combine(profile.asFlow(), user.asFlow()){ profile, user ->
    "${profile.job} ${user.name}"
}

Upvotes: 12

guness
guness

Reputation: 6636

With the help of MediatorLiveData, you can combine results from multiple sources. Here an example of how would I combine two sources:

class CombinedLiveData<T, K, S>(source1: LiveData<T>, source2: LiveData<K>, private val combine: (data1: T?, data2: K?) -> S) : MediatorLiveData<S>() {

    private var data1: T? = null
    private var data2: K? = null

    init {
        super.addSource(source1) {
            data1 = it
            value = combine(data1, data2)
        }
        super.addSource(source2) {
            data2 = it
            value = combine(data1, data2)
        }
    }

    override fun <S : Any?> addSource(source: LiveData<S>, onChanged: Observer<in S>) {
        throw UnsupportedOperationException()
    }

    override fun <T : Any?> removeSource(toRemove: LiveData<T>) {
        throw UnsupportedOperationException()
    }
}

here is the gist for above, in case it is updated on the future: https://gist.github.com/guness/0a96d80bc1fb969fa70a5448aa34c215

Upvotes: 37

Alex Facciorusso
Alex Facciorusso

Reputation: 2408

Many of these answers work, but also it is assumed the LiveData generic types are not-nullable.

But what if one or more of the given input types are nullable types (given the default Kotlin upper bound for generics is Any?, which is nullable)? The result would be even though the LiveData emitter would emit a value (null), the MediatorLiveData will ignore it, thinking it's his own child live data value not being set.

This solution, instead, takes care of it by forcing the upper bound of the types passed to the mediator to be not null. Lazy but needed.

Also, this implementation avoids same-value after the combiner function has been called, which might or might not be what you need, so feel free to remove the equality check there.

fun <T1 : Any, T2 : Any, R> combineLatest(
    liveData1: LiveData<T1>,
    liveData2: LiveData<T2>,
    combiner: (T1, T2) -> R,
): LiveData<R> = MediatorLiveData<R>().apply {
    var first: T1? = null
    var second: T2? = null

    fun updateValueIfNeeded() {
        value = combiner(
            first ?: return,
            second ?: return,
        )?.takeIf { it != value } ?: return
    }

    addSource(liveData1) {
        first = it
        updateValueIfNeeded()
    }
    addSource(liveData2) {
        second = it
        updateValueIfNeeded()
    }
}

Upvotes: 3

Alessandro Scarozza
Alessandro Scarozza

Reputation: 4438

without custom class

MediatorLiveData<Pair<Foo?, Bar?>>().apply {
    addSource(fooLiveData) { value = it to value?.second }
    addSource(barLiveData) { value = value?.first to it }
}.observe(this) { pair ->
    // TODO
}

Upvotes: 11

Blundell
Blundell

Reputation: 76506

If you want to create a field and setup at construction time (use also):

val liveData1 = MutableLiveData(false)
val liveData2 = MutableLiveData(false)

// Return true if liveData1 && liveData2 are true
val liveDataCombined = MediatorLiveData<Boolean>().also {
    // Initial value
    it.value = false
    // Observing changes
    it.addSource(liveData1) { newValue ->
        it.value = newValue && liveData2.value!!
    }
    it.addSource(selectedAddOn) { newValue ->
        it.value = liveData1.value!! && newValue
    }
}

Upvotes: 1

Evgenii Doikov
Evgenii Doikov

Reputation: 431

if you want both value not null

fun <T, V, R> LiveData<T>.combineWithNotNull(
        liveData: LiveData<V>,
        block: (T, V) -> R
): LiveData<R> {
    val result = MediatorLiveData<R>()
    result.addSource(this) {
        this.value?.let { first ->
            liveData.value?.let { second ->
                result.value = block(first, second)
            }
        }
    }
    result.addSource(liveData) {
        this.value?.let { first ->
            liveData.value?.let { second ->
                result.value = block(first, second)
            }
        }
    }

    return result
}

Upvotes: 2

Marek Kondracki
Marek Kondracki

Reputation: 1427

You can use my helper method:

val profile = MutableLiveData<ProfileData>()

val user = MutableLiveData<CurrentUser>()

val title = profile.combineWith(user) { profile, user ->
    "${profile.job} ${user.name}"
}

fun <T, K, R> LiveData<T>.combineWith(
    liveData: LiveData<K>,
    block: (T?, K?) -> R
): LiveData<R> {
    val result = MediatorLiveData<R>()
    result.addSource(this) {
        result.value = block(this.value, liveData.value)
    }
    result.addSource(liveData) {
        result.value = block(this.value, liveData.value)
    }
    return result
}

Upvotes: 121

EpicPandaForce
EpicPandaForce

Reputation: 81549

You can define a method that would combine multiple LiveDatas using a MediatorLiveData, then expose this combined result as a tuple.

public class CombinedLiveData2<A, B> extends MediatorLiveData<Pair<A, B>> {
    private A a;
    private B b;

    public CombinedLiveData2(LiveData<A> ld1, LiveData<B> ld2) {
        setValue(Pair.create(a, b));

        addSource(ld1, (a) -> { 
             if(a != null) {
                this.a = a;
             } 
             setValue(Pair.create(a, b)); 
        });

        addSource(ld2, (b) -> { 
            if(b != null) {
                this.b = b;
            } 
            setValue(Pair.create(a, b));
        });
    }
}

If you need more values, then you can create a CombinedLiveData3<A,B,C> and expose a Triple<A,B,C> instead of the Pair, etc. Just like in https://stackoverflow.com/a/54292960/2413303 .

EDIT: hey look, I even made a library for you that does that from 2 arity up to 16: https://github.com/Zhuinden/livedata-combinetuple-kt

Upvotes: 5

Damia Fuentes
Damia Fuentes

Reputation: 5503

I did an approach based on @guness answer. I found that being limited to two LiveDatas was not good. What if we want to use 3? We need to create different classes for every case. So, I created a class that handles an unlimited amount of LiveDatas.

/**
  * CombinedLiveData is a helper class to combine results from multiple LiveData sources.
  * @param liveDatas Variable number of LiveData arguments.
  * @param combine   Function reference that will be used to combine all LiveData data results.
  * @param R         The type of data returned after combining all LiveData data.
  * Usage:
  * CombinedLiveData<SomeType>(
  *     getLiveData1(),
  *     getLiveData2(),
  *     ... ,
  *     getLiveDataN()
  * ) { datas: List<Any?> ->
  *     // Use datas[0], datas[1], ..., datas[N] to return a SomeType value
  * }
  */
 class CombinedLiveData<R>(vararg liveDatas: LiveData<*>,
                           private val combine: (datas: List<Any?>) -> R) : MediatorLiveData<R>() {

      private val datas: MutableList<Any?> = MutableList(liveDatas.size) { null }

      init {
         for(i in liveDatas.indices){
             super.addSource(liveDatas[i]) {
                 datas[i] = it
                 value = combine(datas)
             }
         }
     }
 }

Upvotes: 5

d-feverx
d-feverx

Reputation: 1672

LiveData liveData1 = ...;
 LiveData liveData2 = ...;

 MediatorLiveData liveDataMerger = new MediatorLiveData<>();
 liveDataMerger.addSource(liveData1, value -> liveDataMerger.setValue(value));
 liveDataMerger.addSource(liveData2, value -> liveDataMerger.setValue(value));

Upvotes: 2

Daniel Wilson
Daniel Wilson

Reputation: 19824

Jose Alcérreca has probably the best answer for this:

fun blogpostBoilerplateExample(newUser: String): LiveData<UserDataResult> {

    val liveData1 = userOnlineDataSource.getOnlineTime(newUser)
    val liveData2 = userCheckinsDataSource.getCheckins(newUser)

    val result = MediatorLiveData<UserDataResult>()

    result.addSource(liveData1) { value ->
        result.value = combineLatestData(liveData1, liveData2)
    }
    result.addSource(liveData2) { value ->
        result.value = combineLatestData(liveData1, liveData2)
    }
    return result
}

Upvotes: 9

Related Questions