Search code examples
androidandroid-livedatamutablelivedata

LiveData does not update


class RequestViewModel(private val repository: RequestRepository) : ViewModel() {

// request currency type
private val currencySearchType = MutableLiveData<String>()

val requests: LiveData<PagedList<Request>> = repository.getRequests(currencySearchType.value!!)

fun updateSearchType(type: String) {
    currencySearchType.postValue(type)
}}

above is the code in my viewModel.

private fun initAdapter() {
        recyclerView.adapter = adapter
        viewModel.requests.observe(viewLifecycleOwner, Observer {
            adapter.submitList(it)
        })
} 

and this is the code in fragment. So basically, what i'm doing is I observe "requests" in viewModel, and in fragment, I will also call updateSearchType to update the currencySearchType. I was hoping that once currencySearchType changed, then the viewmodel.requests will change too. But it turns out the requests never gotta called again. Does anyone know where it went wrong? Appreciate for the help!


Solution

  • Changing the value of currencySearchType does not triggers live data you just using it as function parameter. You have to use Transformation for this.

    https://developer.android.com/reference/android/arch/lifecycle/Transformations

    class RequestViewModel(private val repository: RequestRepository) : ViewModel() {
    
    // request currency type
    lateinit var currencySearchType:String
    
    val requests: LiveData<PagedList<Request>> = Transformations.switchMap(currencySearchType) { repository.getRequests(it) }
    
    fun updateSearchType(type: String) {
        currencySearchType = type
    }}