collectData

fun <T> collectData(source: suspend () -> Flow<T>, onResult: Result<T>.() -> Unit)(source)

Collects a Flow returned by source on Dispatchers.IO and delivers each Result to onResult on Dispatchers.Main.

Errors are caught and forwarded as Result.failure — the ViewModel scope is never cancelled by a failing source.

collectData(
source = { repository.observeMessages() },
onResult = { result ->
result
.onSuccess { messages ->
updateState { copy(messages = messages) }
}
.onFailure { error ->
sendEvent(MessagesEvent.ShowError(error.message ?: ""))
}
}
)

Parameters

source

Suspending factory returning the Flow to collect, executed on IO.

onResult

Callback receiving a Result for each emission or terminal error, always invoked on the Main dispatcher.

Type Parameters

T

The type of values emitted by the flow.