我不知道为什么我的mediatorLiveData无法更新?我还在我的活动文件中设置了观察者。我想做的是
我按照似乎无效的顺序进行操作。我还在构造调用期间初始化了我的第一点。还是一样的问题。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.ktMainViewModel类: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")
}
}
}
}
每次访问变量时都在创建一个新实例
val mediatorLiveData: MediatorLiveData<String>
get() = MediatorLiveData()
val _livedata1: MutableLiveData<String>
get() = MutableLiveData<String>()
更改为
val mediatorLiveData: MediatorLiveData<String> = MediatorLiveData()
val _livedata1: MutableLiveData<String> = MutableLiveData<String>()