asAsyncResult

fun <L, R> Flow<Either<L, R>>.asAsyncResult(startWithLoading: Boolean = true): Flow<AsyncResult<R>>

Transforms a Flow of Either into a Flow of AsyncResult, converting each Either.Left to an Error with metadata, and each Either.Right to a Success.

This is useful for converting flows from Arrow-based APIs into AsyncResult flows, enabling seamless integration with AsyncResult operators and UI patterns.

Behavior:

Example:

sealed class UserError {
object NotFound : UserError()
data class NetworkError(val code: Int) : UserError()
}

val userFlow: Flow<Either<UserError, User>> = userRepository.observeUser()

userFlow.asAsyncResult()
.collect { result ->
when (result) {
is Loading -> showLoading()
is Success -> showUser(result.value)
is Error -> {
val userError = result.metadataOrNull<UserError>()
showError(userError)
}
is NotStarted -> { }
}
}

Return

A Flow of AsyncResult wrapping the Either values.

Parameters

startWithLoading

Whether to emit Loading before the first value. Defaults to true.


@JvmName(name = "asAsyncResultWithLeftThrowable")
fun <R> Flow<Either<Throwable, R>>.asAsyncResult(startWithLoading: Boolean = true): Flow<AsyncResult<R>>

Transforms a Flow of Either with a Throwable on the left side into a Flow of AsyncResult, converting each Either.Left to an Error with the throwable, and each Either.Right to a Success.

This is a specialized version of asAsyncResult for the common case where errors are represented as Throwable. The throwable is stored in Error.throwable instead of Error.metadata.

Behavior:

Example:

val dataFlow: Flow<Either<IOException, Data>> = dataRepository.observeData()

dataFlow.asAsyncResult()
.collect { result ->
when (result) {
is Loading -> showLoading()
is Success -> showData(result.value)
is Error -> showError(result.throwable) // IOException is in throwable
is NotStarted -> { }
}
}

Return

A Flow of AsyncResult wrapping the Either values.

Parameters

startWithLoading

Whether to emit Loading before the first value. Defaults to true.