Created
April 20, 2021 10:37
-
-
Save FarshidABZ/f3cf7512ad8df6534a128ae00c8b97c1 to your computer and use it in GitHub Desktop.
DoubleTriggerLiveData to use multiple transformation on an object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.lifecycle.LiveData | |
import androidx.lifecycle.MediatorLiveData | |
/** | |
* DoubleTriggerLiveData to use multiple transformation on an object | |
* */ | |
class DoubleTriggerLiveData<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 } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If each searchQuery or forceToRefresh value changed, getProducts() will be call | |
class ExampleViewModel : ViewModel() { | |
val isLoading = MutableLiveData<Boolean>() | |
var searchQuery = MutableLiveData<String>().apply { value = "" } | |
private val forceToRefresh = MutableLiveData<Boolean>().apply { value = true } | |
private val doubleTriggerLiveData = DoubleTriggerLiveData(searchQuery, forceToRefresh) | |
val catalogList: MutableLiveData<List<CatalogUIModel>> | |
get() = _catalogList as MutableLiveData<List<CatalogUIModel>> | |
private var _catalogList: LiveData<List<CatalogUIModel>> = doubleTriggerLiveData.switchMap { | |
isLoading.value = true | |
getProducts() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment