1

根据我对导航图范围视图模型onCleared的理解,当从导航堆栈中弹出关联的导航图时,应该立即调用它们的方法。我所看到的是,它需要更多的导航调用,直到onCleared实际被调用。

MainActivity.kt 内部:

val swipeDismissableNavController = rememberSwipeDismissableNavController()

swipeDismissableNavController.addOnDestinationChangedListener(NavController.OnDestinationChangedListener { controller, destination, arguments ->
    try {
        controller.getBackStackEntry("chat")
    } catch(e: IllegalArgumentException) {
        Log.d(TAG, "Not on stack")
    }
    Log.d(TAG, "Route: " + destination.route)
})

SwipeDismissableNavHost(
    navController = swipeDismissableNavController,
    startDestination = "home"
) {
    navigation(
        startDestination = "messages",
        route = "chat"
    ) {
        composable(
            route = "messages"
        ) { 
            val backStackEntry = remember { swipeDismissableNavController.getBackStackEntry("chat") }
            val chatViewModel: ChatViewModel = viewModel(backStackEntry)
            
            ...
        }
        
        composable(
            route = "image"
        ) { 
            val backStackEntry = remember { swipeDismissableNavController.getBackStackEntry("chat") }
            val chatViewModel: ChatViewModel = viewModel(backStackEntry)
            
            ...
        }
    }
    
    ...
}

ChatViewModel.kt 内部

class ChatViewModel(): ViewModel() {
    ...
    
    init {
        Log.d(TAG, "init")
    }

    override fun onCleared() {
        super.onCleared()
        Log.d(TAG, "onCleared")
    }
}

我观察到的是以下行为:
当我导航到chat时,视图模型被正确创建打印init。通过在图中导航chat,视图模型实例被正确地重用。但是,当我导航出chat图表时,我看到它Not on stack正在打印,但onCleared不是。只有经过一些额外的导航,onCleared才会最终打印出来。

有谁知道为什么onCleared被称为延迟?

打印堆栈看起来像:

Not on Stack
Route: home

Route: messages
init

Not on Stack
Route: home
** (THIS IS WHERE I WOULD EXPECT TO SEE onCleared) **

Not on Stack
Route: settings

Not on Stack
Route: home
onCleared

但是,如果我在chat图表中进行更多导航,onCleared则会正确调用:

Not on Stack
Route: home

Route: messages
init

Route: image

Route: messages

Route: image

Route: messages

Route: image

Route: messages

Not on Stack
Route: home
onCleared
4

0 回答 0