简体   繁体   中英

iOS Use RxSwift to track when the async network call has completed

I'm working to integrate RxSwift into my project

I have written an async network request which have result is pass on a callback closure.

Here is my network function

func discoverMovies(for url: String, withPage page: Int, success: @escaping(Bool)->()) {

        let requestUrl = "\(url)&page=\(page)"

        requestGETURL(requestUrl, success: { (json) in

            self.createOrUpdateMoviesList(from: json)   
            success(true)

        }) { (error) in
            print("Could not download due to \(error)")
            success(false)
        }
    }

My question is how can we register an Observable that observe the result of the network call (either success is true or false) so that we can write additional handle base on the result (additional code will only be execute after the network has completed).

I would wrap your functions into Rx-functions:

func discoverMovies(for url: String, withPage page: Int) -> Observable<MoviesList>{
    Observable.create{ observer in 

        let requestUrl = "\(url)&page=\(page)"

        self.requestGETURL(requestUrl, success: { (json) in

            // your createOrUpdateMoviesList(from:) function returns a MoviesList
            let moviesList = self.createOrUpdateMoviesList(from: json)   
            observer.onNext(moviesList)
            observer.onCompleted()

        }) { (error) in
            print("Could not download due to \(error)")
            observer.onError(error)
        }

        return Disposables.create()
    }
}

func otherFunction(withMovies list: MoviesList) -> Observable<Something> {
    // blah blah blah...
}

Now you can chain your Rx-functions with flatMap operator:

discoverMovies(for url: "the url", withPage page: 1)
    .flatMap{ list in 
        otherFunction(withMovies: list)  
    }
    .subscribe(onNext:{ something in
        // ...
    },
     onError: { error in
        // manage errors
    })

You can be sure that your otherFunction() only will be called if discoverMovies() has a success result.

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