Does a function like this make sense? It’s quite o...
# compose
p
Does a function like this make sense? It’s quite often that I have the need to transform a suspend function to a state, so I wonder why there nothing like this built into the runtime 🤔
Copy code
@Composable
  private fun <T> suspendingGet(default: T, get: suspend () -> T): T {
    var value by remember { mutableStateOf(default) }
    LaunchedEffect(Unit) {
      value = get()
    }
    return value
  }
o
Yeah, it is called
produceState
👍
Copy code
@Composable
fun <T> produceState(
    initialValue: T,
    @BuilderInference producer: suspend ProduceStateScope<T>.() -> Unit
): State<T> {
    val result = remember { mutableStateOf(initialValue) }
    LaunchedEffect(Unit) {
        ProduceStateScopeImpl(result, coroutineContext).producer()
    }
    return result
}
116 Views