https://kotlinlang.org logo
#android
Title
# android
o

Olenyov Kirill

07/22/2020, 7:08 AM
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

Javier

07/22/2020, 8:49 AM
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

Olenyov Kirill

07/22/2020, 9:06 AM
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

Javier

07/22/2020, 9:30 AM
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

Olenyov Kirill

07/22/2020, 9:40 AM
Yes, almost like this. But in case of Errors I also throw exception..otherwise we will continue receive events.
m

Mark Murphy

07/22/2020, 11:14 AM
If by
Flow
you mean
Flow
from coroutines, you might consider asking in the #coroutines channel.
👍 1
16 Views