简体   繁体   English

Android ViewModel 观察器不起作用? 科特林

[英]Android ViewModel observer does not work? Kotlin

Inside the fragment of a tabbed activity:在选项卡式活动的片段内:

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    serverSetVM = ViewModelProvider(activity!!).get(ServersViewModel::class.java)

    serverList = ArrayList(serverSetVM.get())
    rv = rv_serverList // findViewById 
    rv.layoutManager = LinearLayoutManager(context)
    rv.adapter = ServerListRevAdapter(context!! ,serverList) 

    serverSetVM.serverSetLiveData.observe(viewLifecycleOwner,  Observer {

        Log.v ("MainAct", "Inside OBSERVER")
        serverList = ArrayList(serverSetVM.get())
        rv.adapter!!.notifyDataSetChanged()
    })
}

Also;还;

val serverSetLiveData = MutableLiveData<HashSet<Server>>() // Inside ViewModel class

observe() function does not seem to work. observe()函数似乎不起作用。 When the value of ServerSetVM is modified inside the same fragment (by the functions defined in ViewModel class, ie add() ), recyclerView is not updated.ServerSetVM的值在同一个片段中被修改时(通过 ViewModel 类中定义的函数,即add() ),recyclerView 不会更新。 According to Logcat output, Observer lambda is called only after onCreateView() .根据 Logcat 输出, Observer lambda 仅在onCreateView()之后调用。

I confirmed MutableLiveData gets updated but Observer{} lambda is not called.我确认 MutableLiveData 已更新,但未调用Observer{} lambda。 Do I need to correct my notion about ViewModels?我需要纠正我对 ViewModel 的看法吗?

EDIT (SOLUTION): Use " = " operator to modify the MutableLiveData value so that observer can detect it.编辑(解决方案):使用“=”运算符修改 MutableLiveData 值,以便观察者可以检测到它。 Even serverSetLiveData.value=serverSetLiveData.value does the job.甚至serverSetLiveData.value=serverSetLiveData.value也能完成这项工作。

Observer only observe if you call setValue() or postValue() method of MutableLiveData Observer 只观察你是否调用了 MutableLiveData 的 setValue() 或 postValue() 方法

where you are calling the setValue() or postValue() function for serverSetLiveData .您正在为 serverSetLiveData 调用 setValue() 或 postValue() 函数的位置。 eg.例如。 serverSetLiveData.setValue(serverList) or serverSetLiveData.postValue(serverList). serverSetLiveData.setValue(serverList) 或 serverSetLiveData.postValue(serverList)。 in the code.在代码中。

仅当您调用.value =才会触发 Obervre

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM