简体   繁体   中英

RXSwift - Waiting multiple API or task to finish

I am new to RxSwift and I would like to achieve something like this. Here's the situation

I have 2 different APIs that needs to populate in a UITableView. Therefore I need to combine 2 sets of data

I would like to achieve something like waiting 2 APIs finish returning the data only then I reload the UITableView once.

I've tried Observable.zip and Observable.combineLatest, but I still cannot get what I want.

Any one can help me on this?

Edited Here's the idea of how I want it to be done

func viewDidLoad() {
    setupObs()
    getBalance()
    getTransaction()
}

func getBalance() {
    //Call get balance
}

func getTransaction() {
    // Call get transaction
}

func setupObs() {
        Observable.zip(
            getBalance(),
            getTransaction()
        )
        .subscribe(onNext: { bal, trx in
            print("Done")
        }, onCompleted: {
            print("completed")
        }).disposed(by: disposeBag)

}

The output "Done" is being printed twice

The Observable.zip operator is exactly the right one to use. Likely though you are doing something else wrong. Your code should look like this:

Observable.zip(firstAPI(), secondAPI()) { firstResult, secondResult in
    combineData(first: firstResult, second: secondResult) // this must return an array!
}
.bind(to: tableView.rx.items) { tableView, row, item in
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: IndexPath(row: row, section: 0))
    // configure cell with item
    return cell
}
.disposed(by: disposeBag)

Likely, your mistake is that you aren't returning an array from the operator and so the rx.items binder is complaining.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM