Issue
Context
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.
Questions
- Are there any reasons for preferring the use of
LaunchedEffect
overrememberCoroutineScope()
inside composable functions? - Is it worth the effort to only create / remember a coroutine scope once per compose tree, or should I just call
rememberCoroutineScope()
in each function where a coroutine is actually launched?
Solution
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
)...
Answered By - nglauber
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.