假设我有一个函数可以接收两个参数 - Observable<String?>
和Observable<Person?
&gt;并返回Observable
这是我的示例代码:
return Observable.combineLatest(self.id, personStream)
map { [weak self] (id,person) -> Person? in
guard let person = person as? Person else {
return nil
}
if let id = id {
// How do I return this updated person
self?.updatePersonDetails(for: person, completion: { (updatedPerson) in
return updatedPerson
})
} else {
return person
}
}
如何在此映射函数中返回此更新的人员?
更新:
public func updatePerson(personStream: Observable<Person>) -> Observable<Person> {
return Observable.combineLatest(
self.id,
personStream
).flatMap { [weak self] (id,person) -> Observable<Person?> in
guard let person = person as? Double else {
return Observable.just(nil)
}
if let id = id {
// How do I return this updated person
return Observable.create { [weak self] observer in
self?.updatePersonDetails(for: person, completion: { (updatedPerson) in
observer.on(.next(updatedPerson))
observer.on(.completed)
})
return Disposables.create()
}
} else {
return Observable.just(person)
}
}
}
上面的函数调用如下:
let personUpdateStream = personService.updatePerson(personStream: personDataStream)
Observable.combineLatest(personUpdateStream, nameStream,profileEnabledStream)
.subscribe(onNext: { [weak self] (person, name, isEnabled) in
print(name)
self?.updatePersonView(person: person, name: name, isLocked: !isEnabled)
})
.disposed(by: disposeBag)
问题:combineLatest与print(name)
内的块永远不会运行。我可以知道这里的问题是什么吗?
personUpdateStream
personUpdateStream RxSwift.FlatMap<(String?, Person?), RxSwift.Observable<Person?>> 0x0000604001e5af70
答案 0 :(得分:1)
您应该使用flatMap
代替map
并整合您应该使用updatePersonDetails
的{Rx Observable.create
来电。
您的最终代码应该类似于:
return Observable.combineLatest(
self.id,
personStream
).flatMap { [weak self] (id,person) -> Observable<Person?> in
guard let person = person as? Double else {
return Observable.just(nil)
}
if let id = id {
// How do I return this updated person
return Observable.create { [weak self] observer in
self?.updatePersonDetails(for: person, completion: { (updatedPerson) in
observer.on(.next(updatedPerson))
observer.on(.completed)
})
return Disposables.create()
}
} else {
return Observable.just(person)
}
}