Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LiveData Transformation not getting triggered

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)
        }
    }
}
like image 815
Dnakin Avatar asked Mar 16 '18 14:03

Dnakin


People also ask

Is LiveData reactive?

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.

What is transformation in LiveData?

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.

What is switchMap in LiveData?

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).


1 Answers

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.

like image 163
Akshay Chordiya Avatar answered Nov 26 '22 17:11

Akshay Chordiya