I'm writing messenger server on grpc with rxjava2 stubs, and I stuck on combining my singles.
I'm have tried some sort of
val user:Single<User> = getUser()
val conversation:Single<Conversation> = getConversation(user.blockingGet())
return conversation.map{
someMethod(user.blockingGet(), conversation.it())
it
}
It looks so unbeauty then all of the examples, so is there a way to combine all of this singles to one line?
First a small comment, usually you don't want to use blockingGet
. Instead you use other combinators to compose your solution and in the end you use subscribe to evaluate it.
I'm assuming you want to combine multiple calls that return a Single
where the result of the next call depends on the previous.
The combinator you are looking for is flatMap
.
val user: Single<User> = getUser()
val singleOfSomething: Single<Conversation> = user.flatMap { user->
getConversation(user).flatMap {conversation ->
someMethod(user, conversation)
}
}
here the return type would be Single
of whatever someMethod
returns.
You would use subscribe
to get that value out when you need it.