Jetpack compose side effects are a way to control the state of your composables. Even though composable functions must to side-effect free, it is unavoidable when dealing with dynamic data. This piece explores SideEffect APIs and how to use them.
LaunchedEffect - running suspend function inside a composable
Suspend function is a piece of code that can be paused and resumed at a later time. Imagine you have a composable that displays a list of jobs, and you're getting this list from a REST API, LaunchedEffect will help run the REST API call once during composition. If the LaunchedEffect is not used then the REST API will be called uncontrollably during every recomposition. It works as follows, When LaunchedEffect enters composition, it launches a coroutine with the parameter passed, The coroutine is cancelled when LaunchedEffect leaves the composition.
- Log analytics
- Run suspend functions on an arbitrary value change (for example during a live search)
- Fetch data from a REST API
The LaunchedEffect API can only be run inside other composable functions. But rememberCoroutineScope is used to launch a coroutine outside of a composable. It is a composable function that returns a CoroutineScope bound to the point of the Composition where it's called. The scope will be cancelled when the call leaves the Composition.