androidandroid-fragmentsandroid-livedataandroid-viewmodelmutablelivedata

Android ViewModel MutableLiveData update multiple times


Scenario

Hi, I have an Activity with a ViewPager. In the ViewPagerAdapter, I create instances of a same fragment with different data. And in each instance I initialize a ViewModel

val dataViewModelFactory = this.activity?.let { DataViewModelFactory(it) }
mainViewModel = ViewModelProviders.of(this, dataViewModelFactory).get(MainViewModel::class.java)

In my fragment, I observe two MutableLiveData when I call APIs

mainViewModel.isResponseSuccessful.observe(this, Observer { it ->

        if(it) {
            //do Something
        }else{
            Toast.makeText(activity, "Error in Sending Request", Toast.LENGTH_SHORT).show()
        }


    })

    mainViewModel.isLoading.observe(this, Observer {
        if (it) {
            println("show progress")
        } else {
            println("dismiss progress")
        }
    })

In each fragment, on a button click I load another fragment. And if required call and API to fetch data.

PROBLEM

The code comes to the observe block multiple times in my fragment. When I comeback from one fragment to previous fragment, even though no API is called, the code on observe block is executed.

What I tried

I tried using an activity instance in the ViewModel initialization

mainViewModel = ViewModelProviders.of(activity,dataViewModelFactory).get(MainViewModel::class.java)

But it did not work.

Please help,


Solution

  • If you want to prevent multiple calls of your observer u can just change MutableLiveData to SingleLiveEvent. Read this