简体   繁体   中英

RxSwift and three API requests

I want to fetch a data from three different APIs, and then save it in a database. Therefore, data from each query should be separated after the operation. How to do it with RxSwift? Zip? In my example I'm using only two URLs, but it's just example.

QueryService:

import Foundation
import RxSwift

class QueryService {

    let albumsURL = URL(string: "https://jsonplaceholder.typicode.com/albums")!


    func fetchAlbums() -> Observable<[Album]> {
        
        return Observable.create { observer -> Disposable in
            
            let task = URLSession.shared.dataTask(with: self.albumsURL) { data, _, _ in
        
                guard let data = data else {
                    observer.onError(NSError(domain: "", code: -1, userInfo: nil))
                    return
                }
        
                do {
                    let albums = try JSONDecoder().decode([Album].self, from: data)
                    observer.onNext(albums)
                } catch {
                    observer.onError(error)
                }
            }
            task.resume()
            return Disposables.create{
                task.cancel()
            }
        }
    }

    func fetchUsers() -> Observable<[User]> {
        
        return Observable.create { observer -> Disposable in
            
            let task = URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/users")!) { data, _, _ in
        
                guard let data = data else {
                    observer.onError(NSError(domain: "", code: -1, userInfo: nil))
                    return
                }
                
                do {
                    let users = try JSONDecoder().decode([User].self, from: data)
                    observer.onNext(users)
                } catch {
                    observer.onError(error)
                }
            }
            task.resume()
            return Disposables.create{
                task.cancel()
            }
        }
    }


}

I'm assuming you're trying to execute two tasks in parallel and want to reach their results from a single observable.

If this is the case, your code should be like this:

Observable.zip(service.fetchAlbums(), service.fetchUsers())
    .subscribe(onNext: { (albums, users) in
        print(albums)
        print(users)
    })
    .disposed(by: self.disposeBag)

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