gpt4 book ai didi

android - 观察者 onChanged 从未调用过

转载 作者:太空狗 更新时间:2023-10-29 15:50:32 29 4
gpt4 key购买 nike

FooActivity.kt:

class FooActivity : AppCompatActivity(), LifecycleRegistryOwner {
override fun getLifecycle(): LifecycleRegistry {
return LifecycleRegistry(this)
}
..
// <-- here mViewModel is null
mViewModel.getBar().observe(this, Observer<List<String>> {
override fun onChanged(bar: List<String>) {
// Never triggered
}
})
mViewModel.init()
// <-- here mViewModel has changed
}

mViewModel 已确认更改。然而,观察者的 onChanged 从未被调用。


问题:为什么不起作用?


编辑:FooViewModel.kt:

class FooViewModel(application: Application) : AndroidViewModel(application) {
val baz: BazPagerAdapter? = null
..
fun init(fm: FragmentManager) {
mBar = listOf("1", "2", "3")
}
..
fun getBar(): List<String> = mBar
..
fun setBaz(pager: ViewPager, periods: List<BazFragment>) {
pager.adapter = BazPagerAdapter(mFragmentManager!!, periods)
}
}

编辑2:

对于 got mentiond,getBar 已经返回 LiveData

fun getBar(): LiveData<List<String>> = mBar

onChange 仍然不会触发。

编辑3:

class FooViewModel(application: Application) : AndroidViewModel(application) {
private var mBar: MutableLiveData<List<String>>? = null
..
fun init(fragmentManager: FragmentManager) {
..
if (mBar == null) {
mBar = MutableLiveData<List<String>>()
}
mBar?.value = periods
}
..
fun getBar(): LiveData<List<String>>? = mBar

最佳答案

List 类型没有观察方法.
ViewModel 也与观察无关,它主要是为了通过配置更改保持状态。

对于您想要的可观察数据(Mutable)LiveData对象。这些是生命周期感知的,并为他们的数据管理观察者。

请参阅代码示例 here :

public class MyViewModel : ViewModel() {
private val mBar = MutableLiveData<List<String>>()

fun getBar(): LiveData<List<String>> = mBar

fun init() {
mBar.setValue(listOf("1", "2", "3"))
}
}

关于android - 观察者 onChanged 从未调用过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44538519/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com