我正在努力将RxSwift集成到我的项目中
我写了一个异步网络请求,其结果是通过回调闭包传递。
这是我的网络功能
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)
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我们如何注册一个Observable观察网络调用结果(成功是对还是失败)的方法,以便我们可以基于结果编写其他句柄(其他代码仅在网络完成后才执行)。
我会将您的函数包装到Rx函数中:
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...
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以将Rx函数与flatMap运算符链接起来:
discoverMovies(for url: "the url", withPage page: 1)
.flatMap{ list in
otherFunction(withMovies: list)
}
.subscribe(onNext:{ something in
// ...
},
onError: { error in
// manage errors
})
Run Code Online (Sandbox Code Playgroud)
您可以确定otherFunction()只有discoverMovies()成功的情况下,您的唯一姓名才会被调用。
| 归档时间: |
|
| 查看次数: |
1308 次 |
| 最近记录: |