Skip to content

Instantly share code, notes, and snippets.

@FarshidABZ
Created April 20, 2021 10:37
Show Gist options
  • Save FarshidABZ/f3cf7512ad8df6534a128ae00c8b97c1 to your computer and use it in GitHub Desktop.
Save FarshidABZ/f3cf7512ad8df6534a128ae00c8b97c1 to your computer and use it in GitHub Desktop.
DoubleTriggerLiveData to use multiple transformation on an object
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 }
}
}
// 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