Match multiple LiveData values ​​in one

So, in development iOSI use ReactiveCocoa, and with this map I can observe several NSObjectsand combine them into signal, which returns the value a. Something like that:

-(RACSignal *)modelIsValidSignal {

    return [RACSignal combineLatest:@[RACObserve(self,username), RACObserve(self,password), RACObserve(self, busyLoggingIn)]
                             reduce:^id(NSString *username, NSString *password, NSNumber *busyLoggingIn) {
                                 return @((username.length > 0) && (password.length > 0 && busyLoggingIn.boolValue == NO));
                             }];
}

So this will return booleanwhich is either false or true. As soon as one of the state of the object changes, this signal will be notified, and it subscriber (Observer)will receive the current value of Boolean.

How do I make something similar using LiveData? the closest to this is MediatorLiveData, but I don’t see how I can observe several events LiveDataat the same time, and then reduce it, as in the example above.

+4
source share
1 answer

I did some verification as

var firstName: MutableLiveData<String> = MutableLiveData()
var lastName: MutableLiveData<String> = MutableLiveData()

var personalDetailsValid: MediatorLiveData<Boolean> = MediatorLiveData()

personalDetailsValid.addSource(firstName, {
    personalDetailsValid.value = lastName.value?.isNotBlank() == true && it?.isNotBlank() ?: false
})

personalDetailsValid.addSource(lastName, {
    personalDetailsValid.value = firstName.value?.isNotBlank() == true && it?.isNotBlank() ?: false
})

Then I observe the usual way

viewModel.personalDetailsValid.observe(this, Observer {
        if (it == true) {
            //Do something
        }
    })

I don't know if this is the recommended way to use LiveData and MediatorLiveData, but it works for me.

0
source

Source: https://habr.com/ru/post/1683826/


All Articles