Android jetpack navigation component result from dialog

后端 未结 3 600
自闭症患者
自闭症患者 2021-02-08 12:44

So far I\'m successfully able to navigate to dialogs and back using only navigation component. The problem is that, I have to do some stuff in dialog and return result to the fr

3条回答
  •  鱼传尺愫
    2021-02-08 13:05

    Thanks to @NataTse and also the official docs, i came up with the extensions so that hopefully less boilerplate code to write:

    fun Fragment.setNavigationResult(key: String, value: T) {
        findNavController().previousBackStackEntry?.savedStateHandle?.set(
            key,
            value
        )
    }
    
    fun Fragment.getNavigationResult(@IdRes id: Int, key: String, onResult: (result: T) -> Unit) {
        val navBackStackEntry = findNavController().getBackStackEntry(id)
    
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_RESUME
                && navBackStackEntry.savedStateHandle.contains(key)
            ) {
                val result = navBackStackEntry.savedStateHandle.get(key)
                result?.let(onResult)
                navBackStackEntry.savedStateHandle.remove(key)
            }
        }
        navBackStackEntry.lifecycle.addObserver(observer)
    
        viewLifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_DESTROY) {
                navBackStackEntry.lifecycle.removeObserver(observer)
            }
        })
    }
    

提交回复
热议问题