Sending Result Back with SavedStateHandle does not work with SavedStateHandle injected in ViewModel.
Getting result using navController.currentBackStackEntry?.savedStateHandle?
it works!
fun CreatePostScreen(
navController: NavController,
coroutineScope: CoroutineScope,
snackbarState: SnackbarHostState,
viewModel: CreatePostViewModel = hiltViewModel(),
) {
LaunchedEffect(key1 = Unit) {
navController.currentBackStackEntry?.savedStateHandle?.getStateFlow(
"result", ""
)?.collect { result ->
Timber.d("Result -> $result")
}
}
}
Using saveStateHandle
injected using Hilt in ViewModel doesn't get the result!
@HiltViewModel
class CreatePostViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
init {
viewModelScope.launch {
savedStateHandle.getStateFlow("result", "").collect {
Timber.d("Result -> $it")
}
}
}
}
That's how I'm sending the result back to the previous screen!
navController.previousBackStackEntry?.savedStateHandle?.set("result", "this is result")
popWithResult
behavior and are doomed to implementViewModel
-specific logic provided we do not want to create a kind ofBaseViewModel
with publicSavedStateHandle
? – Hoon