Jack Guo
Jack Guo

Reputation: 4694

RxJava: how to split Single

How to split a Single stream into separate Single streams, so I can do the following without computing getUserId() twice?

// getUserId() returns Single<String>

getUserId().flatMap { getSomething(it) }  // Return Single<Something>
getUserId().flatMap { getSomethingElse(it) } // Return Single<SomethingElse>

Upvotes: 1

Views: 158

Answers (1)

Sourabh
Sourabh

Reputation: 8482

Cache the result of getUserId using cache

val userIdCached = getUserId().cache()
userIdCached
    .flatMap { getSomething(it) }
    .subscribe(...)
userIdCached
    .flatMap { getSomethingElse(it) }
    .subscribe(...)

Upvotes: 2

Related Questions