Using RxJava2
RxKotlin
and Room
, I need to query the database for an open hunt. That means that I search for a hunt that contains an attribute called closed
with value false
. Once the hunt has been found, it needs to switch the query to that particular hunt.
I have 2 methods for those queries:
getOpenHunt(teamId:String): Flowable<List<Hunt>>
getHunt(huntId:String): Flowable<List<Hunt>>
They both return a List
because otherwise the query gets stuck when no hunt is found.
My idea is something like
fun queryHunt(teamId:String):Flowable<Optional<Hunt>>{
getOpenHunt(teamId)
.map<Optional<Hunt>> {
Optional.create(it.firstOrNull())
}
.switchToFlowableIf ( it is Optional.Some, getHunt(it.element().id)
}
//With switchToFlowableIf's being
fun <E:Any> switchToFlowableIf(condition: (E)->Boolean, newFlowable: Flowable<E>): Flowable<E>
//It should unsubscribe from getOpenHunt and subscribe to newFlowable
For reference, here is my Optional
class
sealed class Optional<out T> {
class Some<out T>(val element: T) : Optional<T>()
object None : Optional<Nothing>()
fun element(): T? {
return when (this) {
is Optional.None -> null
is Optional.Some -> element
}
}
companion object {
fun <T> create(element: T?): Optional<T> {
return if (element != null) {
Optional.Some(element)
} else {
Optional.None
}
}
}
}
Is there a similar method already built in RxJava2? If not, how would you implement it?