gpt4 book ai didi

ios - RxSwift - 使用两个可观察对象进行异步调用

转载 作者:行者123 更新时间:2023-11-28 06:05:06 25 4
gpt4 key购买 nike

假设我有一个接受两个参数的函数 - Observable<String?>Observable<Person? > 并返回 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 中的 block 与 print(name)从不运行。我可以知道这里有什么问题吗?

personUpdateStream 的描述

personUpdateStream RxSwift.FlatMap<(String?, Person?), RxSwift.Observable<Person?>> 0x0000604001e5af70

最佳答案

您应该使用 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)
}
}

关于ios - RxSwift - 使用两个可观察对象进行异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48470605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com