Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To make Arrow-KT's "either" and Kotlin Coroutines' "flow" flat, you can use the flatMap operator on a Flow of Eithers.

To do this, you need to define a function that takes as input an Either and returns a Flow. You can then call the flatMap operator with this function, which will flat-map the Flow of Eithers into a single Flow of values.

For example, let's say you have a Flow of Eithers:

val eitherFlow: Flow<Either<Error, String>>

You can define a function that takes an Either and returns a Flow:

fun <E, A, B> Either<E, A>.flatMap(f: (A) -> Flow<B>): Flow<Either<E, B>> =
    fold(
        { l -> flowOf(Either.left(l)) },
        { r -> f(r).map { Either.right(it) } }
    )

Then you can call flatMap on the Flow of Eithers with this function:

val flatFlow: Flow<Either<Error, String>> = eitherFlow.flatMap { either ->
    either.fold(
        { flowOf(Either.left(it)) },
        { someValue ->
            // Create a flow from the value
            createFlow(someValue)
        }
    )
}

This will return a flat Flow of values of type Either<error, string="">.