In Jetpack compose, we have the option of using rememberCoroutineScope() as well as using the LaunchedEffect composable in order to use coroutines / run suspend functions (show snackbars etc).
The convention I've adopted so far is to remember a single coroutine scope at the top of my compose tree, and pass it down via function arguments to places where it is needed. This vaguely seems like a good practice, but on the other hand it's adding extra noise to my function signatures.
LaunchedEffect over rememberCoroutineScope() inside composable functions?rememberCoroutineScope() in each function where a coroutine is actually launched?Use rememberCoroutineScope() when you are using coroutines and need to cancel and relaunch the coroutine after an event
Use LaunchedEffect() when you are using coroutines and need to cancel and relaunch the coroutine every time your parameter changes and it isn’t stored in a mutable state.
Leaving my understanding here:
Question 1:
LaunchedEffect should be used when you want that some action must be taken when your composable is first launched. For example, when you want to request some data from your ViewModel or run some sort of animation...
rememberCoroutineScope on the other hand, is specific to store the Coroutine scope allowing the code to launch some suspend function...
imho, the only relation between them is that you can also use a LaunchedEffect to launch a coroutine...
Question 2: As you can see in the docs, rememberCoroutineScope will keep the reference of the coroutine's scope in a specific point of the composition. Therefore, if a given composable is removed from the recomposition, that coroutine will be cancelled automatically. For instance, you have the following composable calls A -> B -> C. If you remember the coroutine scope in C and it is removed from the composition, the coroutine is automatically cancelled. But if you remember from A, pass the scope through B and C, use this scope in C, and then C is removed, the coroutine will continue running (because it was remembered in A)...