You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fragment完全销毁后ViewModel未重建问题(Jetpack Navigation+Dagger2)

底部导航嵌套导航图的重定向问题解决

问题背景

应用Activity含底部导航,每个标签对应独立导航图,结构如下:

A --- C
  |     |
\  /   \  /
 \/     \/
  B      D
  • A、C为导航图根节点(对应底部导航标签)
  • B、D为各自导航图下的嵌套页面

问题场景:

  1. 切换至C标签,导航到D页面
  2. 切回A标签后再次切回D(系统保留回栈)
  3. 此时点击返回无法回到C页面,会被自动重定向回D

问题根源分析

直接触发原因

首次从C导航到D时,MasViewModel的navigation LiveData被设置了Route.ProfileEdit.LoanHistory值。切换标签返回C时,MasFragment的onCreate重新执行并观察LiveData,由于ViewModel保留了旧值,会立刻触发handleRoute方法,再次导航到D,形成循环。

ViewModel未重建的核心原因

从Dagger配置来看,MasViewModel未指定自定义Scope,导致Dagger将其依赖提升至AppComponent的@Singleton作用域,成为全局单例。因此无论MasFragment重建多少次,都会拿到同一个ViewModel实例,LiveData的旧值始终残留。

解决方案

1. 给ViewModel绑定对应Scope,打破单例

给MasViewModel添加与MasFragment一致的@PrivateAreaScope,确保ViewModel生命周期与Fragment的作用域绑定,Fragment重建时会生成新的ViewModel实例:

@PrivateAreaScope
class MasViewModel @Inject constructor() : BaseViewModel() {

    private val _navigation = MutableLiveData<Route>()
    internal val navigation: LiveData<Route> = _navigation

    internal fun openLoanHistoryInfo() = run {
        _navigation.value = Route.ProfileEdit.LoanHistory
    }
}

2. 使用一次性事件包装LiveData(兜底方案)

通过一次性事件类,确保LiveData的旧值不会重复触发导航逻辑,即使ViewModel未重建也能解决问题:

先定义一次性事件类:

open class Event<out T>(private val content: T) {

    var hasBeenHandled = false
        private set

    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    fun peekContent(): T = content
}

修改ViewModel的LiveData类型:

class MasViewModel @Inject constructor() : BaseViewModel() {

    private val _navigation = MutableLiveData<Event<Route>>()
    internal val navigation: LiveData<Event<Route>> = _navigation

    internal fun openLoanHistoryInfo() = run {
        _navigation.value = Event(Route.ProfileEdit.LoanHistory)
    }
}

修改Fragment的事件处理逻辑:

private fun handleRoute(event: Event<Route>?) {
    event?.getContentIfNotHandled()?.let { route ->
        when (route) {
            is Route.ProfileEdit.LoanHistory -> findNavController().navigate(
                MasFragmentDirections.actionMasToLoanhistory()
            )
        }
    }
}

3. 优化观察者注册时机

将观察者注册从onCreate移至onViewCreated,并使用viewLifecycleOwner绑定View生命周期,避免内存泄漏:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    viewModel.navigation.observe(viewLifecycleOwner, ::handleRoute)
}

总结

  • 核心问题是MasViewModel被误设为全局单例,导致LiveData旧值残留
  • 优先通过添加对应Scope解决生命周期不匹配问题;同时配合一次性事件处理,彻底避免重复导航

内容的提问来源于stack exchange,提问作者Sergei Mikhailovskii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:55:22