我有一个看起来像这样的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的viewModel中,我希望能够调用navigate(R.id.action_fragmentA_to_fragmentB),但问题是observeNavigationCommands()中的使用者从未收到NavigationCommands
.....
但是,如果我复制observeNavigationCommands()的内容并将其放在我当前的片段(扩展了BaseFragment的片段)中,则消费者会收到更新
我想念什么?请帮忙

最佳答案

我是否正确理解,对于您的扩展了BaseFragment的片段,您想附加一个扩展了BaseViewModel的viewModel,但不适用于liveData吗?
如果是这样,请查看我创建以反射(reflect)您的情况的这个简单的工作项目:
https://github.com/phamtdat/OpenViewModelDemo
关键是使viewModel可覆盖,并在扩展BaseFragment的片段中覆盖它。

关于android - BaseFragment中的LiveData使用者未从BaseViewModel接收更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/65260061/

10-12 01:34