javaandroidkotlinandroid-livedatamediatorlivedata

My MediatorLiveData is not getting updated


I have no clue as to why my mediatorLiveData not get updated? I have also set up the observer in my Activity file. I am trying to do is

  1. click a button that will add source the live data to my mediatorLivedata
  2. another button which will keep changing the livedata so that my mediator livedata should update( changeLiveData1 is the button here)

I do that in the order it doesn't seem to work. Also I initialised during the construction invocation my 1st point. Still the same issue.. MainActivity.kt

class MainActivity : AppCompatActivity() {

    lateinit var viewModel: MainViewModel

    override
    fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)

        viewModel.mediatorLiveData.observe(this, Observer {

            text_view_content.text = it
        })

        livedata1.setOnClickListener {

            viewModel.changeLiveData1()
        }

        livedata2.setOnClickListener {
            viewModel.changeLiveData2()
        }

        add_source.setOnClickListener {
            viewModel.addSourceLivedata1()
        }
    }
}

MainViewModel.kt class MainViewModel : ViewModel() {

val mediatorLiveData: MediatorLiveData<String>
    get() = MediatorLiveData()


val _livedata1: MutableLiveData<String>
    get() = MutableLiveData<String>()


var change = 0
fun changeLiveData1() {
    change++
    _livedata1.value = "chnaged lived data...$change"
}

fun changeLiveData2() {

}


fun addSourceLivedata1() {

    var count = 0
    mediatorLiveData.addSource(_livedata1) {
        count++
        Log.d("MainView", "$count is ")
        if (count > 5) {
            mediatorLiveData.value = "changed from adding source... $count"
        } else {
            mediatorLiveData.value = "count is less than 5"
            Log.d("MainView", "count is $count")
        }
    }

}
}

Solution

  • You are creating a new instance each time you access the variable

    val mediatorLiveData: MediatorLiveData<String>
        get() = MediatorLiveData()
    
    val _livedata1: MutableLiveData<String>
        get() = MutableLiveData<String>()
    

    Change it to

    val mediatorLiveData: MediatorLiveData<String> = MediatorLiveData()
    
    val _livedata1: MutableLiveData<String> = MutableLiveData<String>()