Rxswift: Waiting for two observables to complete

Created on 4 Mar 2016  路  3Comments  路  Source: ReactiveX/RxSwift

I have this problem where I need to listen to the complete-events of two observables and do something when both are complete.

func fetchA() -> Observable<A> {}
func fetchB() -> Observable<B> {}

let a = fetchA();
let b = fetchB();

waitForBoth(a, b).subscribeCompleted {
    // Do stuff now that both have finished
}

Is there any operator or function that does this?

Most helpful comment

If you are just interested in completed event, you can use any of Combining operators, for example zip

let fetch1 = [7].toObservable()
let fetch2 = [12].toObservable()

Observable
    .zip(fetch1, fetch2) { (a, b) throws -> Int in
        print("\(a), \(b)") //7, 12
        return 0
    }
    .subscribeCompleted { print("Done") }

You can choose a proper method depending on what do you want to do with data from fetchA and fetchB.

All 3 comments

If you are just interested in completed event, you can use any of Combining operators, for example zip

let fetch1 = [7].toObservable()
let fetch2 = [12].toObservable()

Observable
    .zip(fetch1, fetch2) { (a, b) throws -> Int in
        print("\(a), \(b)") //7, 12
        return 0
    }
    .subscribeCompleted { print("Done") }

You can choose a proper method depending on what do you want to do with data from fetchA and fetchB.

That'll do, thanks!

is there a way to make zip take an array of Observables vs just two hard coded Observables?

Was this page helpful?
0 / 5 - 0 ratings