我的MediatorLiveData尚未更新

问题描述 投票:0回答:1

我不知道为什么我的mediatorLiveData无法更新?我还在我的活动文件中设置了观察者。我想做的是

  1. 单击将实时数据源添加到我的mediatorLivedata的按钮
  2. 另一个将不断更改实时数据以便我的调解员实时数据更新的按钮(changeLiveData1是此处的按钮)

我按照似乎无效的顺序进行操作。我还在构造调用期间初始化了我的第一点。还是一样的问题。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")
        }
    }

}
}
java android kotlin android-livedata mediatorlivedata
1个回答
0
投票

每次访问变量时都在创建一个新实例

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

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

更改为

val mediatorLiveData: MediatorLiveData<String> = MediatorLiveData()

val _livedata1: MutableLiveData<String> = MutableLiveData<String>()
© www.soinside.com 2019 - 2024. All rights reserved.