【发布时间】:2021-03-23 09:11:59
【问题描述】:
我有一个看起来像这样的 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 类看起来像
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 的片段)中,消费者会收到更新
我错过了什么?请帮忙
【问题讨论】:
标签: android kotlin mvvm android-livedata