Is it okay to launch another coroutine inside `Lau...
# compose
f
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
Copy code
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
    }
}
d
yes it is
1
a
You can use
collectLatest
instead of launching a new coroutine.
f
Thank you both!
collectLatest
makes sense actually
guess it depends if you want to cancel the previous snackbar when you show another one or not
s
Going forward, if you face another instance where your first instinct is to nest your coroutine, take a step back and observe the performance of your code. 🤓
f
@sorianog What do you mean exactly?
s
Run your code and observe your app/logic to see if the behavior is ideal. This will help you drill down if your logic is truly accomplishing what you expected it to.
g
I would only partial agree with Gerald's suggestion: If everything you are doing is "obviously" limited to the UI thread, then I'd agree. If however, you are either relying on the execution to run after the current UI process ends OR calling an interface that might in the future be expanded to interact outside of the UI thread, then I would say stick to the coroutine
1
s
Thanks for the specifics George!
👍 1
f
Sometimes it's useful to have another pair of eyes
1