What is the difference between `LaunchedEffect` an...
# compose
a
What is the difference between
LaunchedEffect
and
remember
?
LaunchedEffect
uses
remember
internally.
Copy code
@Composable
@NonRestartableComposable
@OptIn(InternalComposeApi::class)
fun LaunchedEffect(
    key1: Any?,
    block: suspend CoroutineScope.() -> Unit
) {
    val applyContext = currentComposer.applyCoroutineContext
    remember(key1) { LaunchedEffectImpl(applyContext, block) }
}
The additions I see in
LaunchedEffect
, 1. coroutine scope 2. Returns the calculated data.
If I don’t need coroutine scope and the returned data will not be used as the
block
updates another mutable state in the Composable, should I use
remember
or
LaunchedEffect
?
Example
Copy code
@Composable
fun Test(
  para1: Int,
) {
  var result = remember {
    mutableStateOf("")
  }

  remember(para1) {
    aMethodsWithCallbacks() { updatedResult: String -> 
        result = updatedResult
    }
  }

  return result
}
vs
Copy code
@Composable
fun Test(
  para1: Int,
) {
  var result = remember {
    mutableStateOf("")
  }

  LaunchedEffect(para1) {
    aMethodsWithCallbacks() { updatedResult: String -> 
        result = updatedResult
    }
  }

  return result
}
c
remember is generally used for any state you need persisted between recompositions. LaunchedEffect is a specific side effect: https://developer.android.com/jetpack/compose/side-effects
a
To add, Both works as intended (it seems like that so far) So, checking on the preferred approach.
c
It’s not really one over the other. LaunchedEffect has a specific use case, as detailed in the documentation
m
If you have a piece of state that needs to be remembered across re-composition, you would use remember (usually with "mutableStateOf"). LaunchedEffect is for running a coroutine that has side effects. How often and when the coroutine launches depends on the "key" parameters as detailed in the documents mentioned above.
261 Views