One Off the Slack: Is It Safe to Nest Coroutines?

Florian Walther asked:

Is it okay to launch another coroutine inside LaunchedEffect by wrapping it inside a launch block? Otherwise the showSnackbar method blocks the coroutine because it’s a suspend fun

LaunchedEffect(Unit) {
    viewModel.events.collect { event ->
        when (event) {
            is RewardListViewModel.Event.ShowUndoRewardSnackbar -> {
                launch {
                    val snackbarResult = scaffoldState.snackbarHostState.showSnackbar(
                        message = context.getString(R.string.reward_deleted),
                        actionLabel = context.getString(R.string.undo),
                    )
                    if (snackbarResult == SnackbarResult.ActionPerformed) {
                        viewModel.onUndoDeleteRewardConfirmed(event.reward)
                    }
                }
                Unit
            }
            is RewardListViewModel.Event.NavigateToEditRewardScreen -> {
                navController.navigate(AddEditRewardScreenSpec.buildRoute(event.reward.id))
            }
        }.exhaustive
    }
}

Dominic Fisher was succinct: “yes it is”.

Albert Chang suggested using collectLatest() instead of collect(), to which Florian responded:

collectLatest makes sense actually

guess it depends if you want to cancel the previous snackbar when you show another one or not


Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!