我有两种方法:
func rxGetAllTonicsForLanguage(language: Language) -> Observable<AnyObject?>
func saveTonics(list: [Tonic]) -> Observable<AnyObject?>
现在我想首先执行getAllTonics调用,然后使用该调用的结果我想要执行下一个操作。所以我认为这是我可以用FlatMap做的事情。但我已经陷入困境,我无法弄清楚如何将这些链接起来。
我尝试过如下:
self.remoteService.rxGetAllTonicsForLanguage(language)
.subscribeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
.flatMap{tonics -> Observable<[Tonic]> in
print("Tonics: \(tonics)")
let x = tonics as! [Tonic]
return TonicAdapter.sharedInstance.saveTonics(x)
}.observeOn(MainScheduler.instance)
.subscribe({ e in
switch e {
case .Next(let element):
if let result = element as? String {
DDLogDebug("Saved something \(result)")
}
case .Error(let e):
DDLogError("Error in save tonics \(e)")
case .Completed:
DDLogDebug("Completed save tonics")
}
}
).addDisposableTo(self.disposeBag)
它在返回TonicAdapter的行上给出了这个错误:
Cannot convert return expression of type 'Observable<AnyObject?>' (aka 'Observable<Optional<AnyObject>>') to return type 'Observable<[Tonic]>' (aka 'Observable<Array<Tonic>>')
我没有看到问题,因为两种方法都返回了Observables?
答案 0 :(得分:2)
您需要将saveTonics中声明的返回类型从Observable更改为Observable&lt; [Tonic]&gt;。或者您可以进行相同的更改(如果您确定总是如此)。
答案 1 :(得分:0)
func rxGetAllTonicsForLanguage(language: Language) -> Observable<[Tonic]>
func saveTonics(list: [Tonic]) -> Observable<AnyObject?>
rxGetAllTonicsForLanguage的输出可以像这样传递给saveTonics
rxGetAllTonicsForLanguage
.flatMapLatest(saveTonics)
.subscribe(...)
.disposed(by: disposeBag)