Hi. How can I zip two flows when each flow’s resul...
# android
o
Hi. How can I zip two flows when each flow’s result is represented like sealed class? sealed class Response<out T> { object Loading ... data class Data<T>(val data: T)... data class Error(val error: Throwable)... } I see there is Flow.zip() operator but anyway it’s a lot of combinations and I have no idea how to cancel flow when one of the error received.. So, what’s the best Kotlin/Flow approach to deal with it?
j
Check for
combine
or
combineTransform
flow functions. You should create a function or extension function to combine your resource flows easily.
Copy code
fun <T1, T2, T3> Flow<Resource<T1>>.combine(resourceFlow: Flow<Resource<T2>): Flow<Resource<R3>>
o
Yeah. But what do we need to do if first Resource is in Error state and the second in the Loading state? This is soft of terminal case. We have to construct new error state, abort the flow and ignore all next events..The only idea I have is to throw exception, catch it and reemit error state..
j
It depends of your usecase, but probably if one of the resources is error, you should stop collect and show an error.
You doesn't need to throw exceptions. You can have a
when
which checks both resource states.
Copy code
when {
    this is Error -> this
    resource is Error -> resource
    this is Success && resource is Success -> Success(success(this.data, resource.data))
    this is Loading || resource is Loading -> Loading
    else -> throw IllegalStateException("This state should not be possible")
}
o
Yes, almost like this. But in case of Errors I also throw exception..otherwise we will continue receive events.
m
If by
Flow
you mean
Flow
from coroutines, you might consider asking in the #coroutines channel.
👍 1