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="">.
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
Asked: 2023-06-06 21:51:29 +0000
Seen: 21 times
Last updated: Jun 06 '23
Why can't IntelliJ IDEA detect the Kotlin multiplatform library?
How to implement map function on Kotlin's Stateflow?
What is the correlation between coroutines and the Kotlin Gradle Plugin?
When the library throws a JsonDataException, why does the Kotlin Moshi adapter return null?
What are the typical approaches found in a Gradle build script?
Which languages are appropriate to use for a contemporary website?