Jack Guo
Jack Guo

Reputation: 4714

Execute something when multiple Singles finish (aka combineLatest for Single)

I want to execute something when both units and variables are set (through Single<T>, NOT Observable). How to do that?

// getUserId(), getSomething(), getSomethingElse() all return Single<T>

getUserId().flatMap { getSomething(it) }.subscribe({ data -> units = data }) 
getUserId().flatMap { getSomethingElse(it) }.subscribe({ data -> variables = data }) 

execute(units, variables)

Upvotes: 0

Views: 182

Answers (1)

Benjamin
Benjamin

Reputation: 7368

You can use the Zip operator:

val name = Single.just("Jake")
val age = Single.just(26)

Single.zip<String, Int, String>(name, age, BiFunction { n, a -> "$n is $a years old" })
        .subscribe { result -> print(result) }

will print "Jake is 26 years old".

Upvotes: 5

Related Questions