Ask Your Question
1

What is the method to make Arrow-KT's "either" and Kotlin Coroutines' "flow" flat?

asked 2023-06-06 21:51:29 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-06 21:52:02 +0000

david gravatar image

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="">.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-06 21:51:29 +0000

Seen: 21 times

Last updated: Jun 06 '23