I subscribed to ids
and search
in the ui but i wasn't getting any results so i stepped through with the debugger and found out that the transformation is not getting triggered after the first time. So when i call setIds
the first time ids
gets updated but for every call after the first one the transformation won't trigger. Same goes for the search
.
Any ideas what might possible go wrong?
class MyViewModel : ViewModel() {
private val repository = Repository.sharedInstance
var recentRadius: LiveData<List<RecentRadius>>?
var recentRoute: LiveData<List<RecentRoute>>?
init {
recentRadius = repository.recentRadius()
recentRoute = repository.recentRoute()
}
private val idsInput = MutableLiveData<String>()
fun setIdsInput(textId: String) {
idsInput.value = textId
}
val ids: LiveData<List<String>> = Transformations.switchMap(idsInput) { id ->
repository.ids(id)
}
private val searchInput = MutableLiveData<Search>()
fun setSearchInput(search: Search) {
searchInput.value = search
}
val search: LiveData<SearchResult> = Transformations.switchMap(searchInput) { search ->
when (search.type) {
SearchType.ID -> repository.id(search)
SearchType.RADIUS -> repository.radius(search)
SearchType.ROUTE -> repository.route(search)
}
}
}
If you try to find a definition for LiveData, you'll find that it's a “reactive, observable, lifecycle-aware data holder”. We know it can be observed, and we know it holds 1 data value that is re-emitted for any new observer (and any changes made to it are also emitted), just like any BehaviorRelay.
Transformation methods for LiveData . These methods permit functional composition and delegation of LiveData instances. The transformations are calculated lazily, and will run only when the returned LiveData is observed. Lifecycle behavior is propagated from the input source LiveData to the returned one.
The point is the returned value of Transformations. switchMap is MediatorLiveData which adds new LiveData reference to as a new source (and deactivates the other sources).
The most common reason why transformation don't get triggered is when there is no Observer
observing it or the input LiveData
is not getting changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With