collectAsState

Functions summary

State<R>
@Composable
<T : R, R : Any?> Flow<T>.collectAsState(initial: R, context: CoroutineContext)

Collects values from this Flow and represents its latest value via State.

Cmn
State<T>

Collects values from this StateFlow and represents its latest value via State.

Cmn

Functions

Flow.collectAsState

@Composable
fun <T : R, R : Any?> Flow<T>.collectAsState(
    initial: R,
    context: CoroutineContext = EmptyCoroutineContext
): State<R>

Collects values from this Flow and represents its latest value via State. Every time there would be new value posted into the Flow the returned State will be updated causing recomposition of every State.value usage.

import androidx.compose.material.Text
import androidx.compose.runtime.collectAsState

val value: String by flow.collectAsState("initial")
Text("Value is $value")
Parameters
initial: R

the value of the state will have until the first flow value is emitted.

context: CoroutineContext = EmptyCoroutineContext

CoroutineContext to use for collecting.

StateFlow.collectAsState

@Composable
fun <T : Any?> StateFlow<T>.collectAsState(
    context: CoroutineContext = EmptyCoroutineContext
): State<T>

Collects values from this StateFlow and represents its latest value via State. The StateFlow.value is used as an initial value. Every time there would be new value posted into the StateFlow the returned State will be updated causing recomposition of every State.value usage.

import androidx.compose.material.Text
import androidx.compose.runtime.collectAsState

val value: String by stateFlow.collectAsState()
Text("Value is $value")
Parameters
context: CoroutineContext = EmptyCoroutineContext

CoroutineContext to use for collecting.