https://kotlinlang.org logo
#compose
Title
# compose
f

Florian Walther (live streaming)

12/30/2021, 11:57 AM
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

Dominaezzz

12/30/2021, 11:59 AM
yes it is
1
a

Albert Chang

12/30/2021, 12:01 PM
You can use
collectLatest
instead of launching a new coroutine.
f

Florian Walther (live streaming)

12/30/2021, 12:04 PM
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

sorianog

12/30/2021, 2:06 PM
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

Florian Walther (live streaming)

12/30/2021, 2:54 PM
@sorianog What do you mean exactly?
s

sorianog

12/30/2021, 2:57 PM
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

GeorgeS-Litesoft

12/30/2021, 2:57 PM
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

sorianog

12/30/2021, 2:58 PM
Thanks for the specifics George!
👍 1
f

Florian Walther (live streaming)

12/31/2021, 10:30 AM
Sometimes it's useful to have another pair of eyes
1
6 Views