[英]LiveData Consumer in BaseFragment not receiving updates from BaseViewModel
我有一个看起来像这样的 BaseFragment.kt
open class BaseFragment: Fragment() {
private lateinit var viewModel: BaseViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(this).get(BaseViewModel::class.java)
observeNavigationCommands()
}
/**
* Method that observes Navigation commands triggered by BaseViewHolder
* This allows us to navigate from a viewHolder using the MVVM pattern
*/
private fun observeNavigationCommands() {
viewModel.navigationCommands.observe(viewLifecycleOwner, EventObserver {
Timber.e("received nav command $it")
when(it) {
is NavigationCommand.To -> findNavController().navigate(it.destinationId)
is NavigationCommand.Back -> findNavController().popBackStack()
is NavigationCommand.BackTo -> TODO()
NavigationCommand.ToRoot -> TODO()
}
})
}
}
...和一个看起来像这样的 BaseViewModel.kt
open class BaseViewModel: ViewModel() {
val navigationCommands = MutableLiveData<Event<NavigationCommand>>()
/**
* Navigate to a specific fragment using Id
*/
fun navigate(id: Int) {
Timber.e("trigger navigation event $id")
// navigationCommands.postValue(NavigationCommand.To(id))
navigationCommands.value = Event(NavigationCommand.To(id))
}
/**
* Pop backStack
*/
fun goBack() {
navigationCommands.value = Event(NavigationCommand.Back)
}
}
NavigationCommand
class 看起来像
sealed class NavigationCommand {
data class To(val destinationId: Int) : NavigationCommand()
data class BackTo(val destinationId: Int): NavigationCommand()
object Back: NavigationCommand()
object ToRoot: NavigationCommand()
}
现在在我扩展BaseViewModel
的其他视图模型中,我希望能够调用navigate(R.id.action_fragmentA_to_fragmentB)
但问题是observeNavigationCommands()
中的消费者永远不会收到 NavigationCommands
......
但是,如果我复制observeNavigationCommands()
的内容并将其放在我当前的片段(扩展BaseFragment
的片段)中,消费者会收到更新
我错过了什么? 请帮忙
我是否理解正确,对于扩展BaseFragment
的片段,您想附加一个扩展BaseViewModel
的视图模型,但这不适用于 liveData?
如果是这样,请查看我为反映您的情况而创建的这个简单的工作项目:
https://github.com/phamtdat/OpenViewModelDemo
关键是使viewModel
覆盖并在扩展BaseFragment
的片段中覆盖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.