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
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")
}
}
}
}
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>()