我想映射一个字典 和flatMap一起返回一个新的Observable。 我正在尝试Observable,因为我可能是一个单个对象或一个对象数组。
func fetchRibsList() -> Observable<[LCLRibAccount]> {
return provider.rxDict(service: .fetchRibsList)
.map({ (dict, _) -> [String: Any] in
return dict
})
.filter({ dict -> Bool in
dict["ribs"] != nil
})
.filter({ dict -> Bool in
dict["rib"] != nil
})
.flatMap({ dict -> Observable<Any> in
//return either list of ribs or 1 single rib
if let ribs = dict["ribs"] as? [String: Any] {
return Observable.just(LCLRib.parseAccountList(with: ribs))
}
if let rib = dict["rib"] as? [String: Any] {
return Observable.just(LCLRib.parseRib(with: rib))
}
return Observable.empty()
})
}
是否可以包含带有2个flatMap的条件并返回一个数组或一个单个对象 问题是我需要具体使用Observable类型:
这是我得到的错误:无法转换类型&#39; Observable&#39;的返回表达式返回类型&#39; Observable&lt; [LCLRibAccount]&gt;&#39;
答案 0 :(得分:0)
问题是你的函数的返回类型func fetchRibsList() -> Observable<[LCLRibAccount]>
。它期望一个数组的Observable。也许你可以将单个对象包装在一个数组中。像这样:
func fetchRibsList() -> Observable<[LCLRibAccount]> {
return provider.rxDict(service: .fetchRibsList)
.map({ (dict, _) -> [String: Any] in
return dict
})
.filter({ dict -> Bool in
dict["ribs"] != nil
})
.filter({ dict -> Bool in
dict["rib"] != nil
})
.flatMap({ dict -> Observable<[LCLRibAccount]> in
//return either list of ribs or 1 single rib
if let ribs = dict["ribs"] as? [String: Any] {
return Observable.just(LCLRib.parseAccountList(with: ribs))
}
if let rib = dict["rib"] as? [String: Any] {
return Observable.just([LCLRib.parseRib(with: rib)]) //wrap single object in array
}
return Observable.empty()
})
}