Composable Function

produceState

Return an observable snapshot State that produces values over time without a defined data source.

ProduceState

@Sampled
@Composable
fun ProduceState(viewModel: ProduceStateSampleViewModel) {
    val uiState by
        produceState<UiState<List<Person>>>(UiState.Loading, viewModel) {
            viewModel.people.map { UiState.Data(it) }.collect { value = it }
        }

    when (val state = uiState) {
        is UiState.Loading -> Text("Loading...")
        is UiState.Data ->
            Column {
                for (person in state.data) {
                    Text("Hello, ${person.name}")
                }
            }
    }
}

ProduceStateAwaitDispose

@Suppress("UNUSED_VARIABLE")
@Sampled
@Composable
fun ProduceStateAwaitDispose(viewModel: ProduceStateSampleViewModel) {
    val currentPerson by
        produceState<Person?>(null, viewModel) {
            val disposable = viewModel.registerPersonObserver { person -> value = person }

            awaitDispose { disposable.dispose() }
        }
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: