I have an object created from flatMap
ing an observable.
private lazy var childObj: chilView? = {
let keychainStore = Realm().getStore()
let selectedElementID = keychainStore.elementID
.asObservable()
.distinctUntilChanged {$0 == $1}
.flatMap({ (elementID) -> Observable<Element?> in
guard let elementID = elementID else {
return Observable.error(Errors.InvalidElementID)
}
return Observable.create { observer in
let elementStream: Observable<Result<Element>> = keychainStore.getObservable(id: elementID)
elementStream.subscribe(onNext: { (result) in
switch result {
case .success(let element):
observer.onNext(element)
default: break
}
})
.disposed(by: self.disposeBag)
return Disposables.create()
}
})
return self.createChildObject(with: selectedElementID)
}()
The selectedElement is of type flatMap observable. createChildObject(with:)
is called even before observer.onNext(element)
is executed. How do I fix this?
I am not sure I completely understand your problem from the description but here are some thoughts:
It's not a race condition. Your selectedElementID
chain and the flatMap
code within it will not be executed before you subscribe
to the selectedElementID
. So I guess you subscribe to the selectedElementID
somewhere within createChildObject
method and obviously get the createChildObject
code executed before the selectedElementID
chain.
Depending on how keychainStore
rx calls are designed and how you subscribe to selectedElementID
observable you might get a race condition but I am not sure that the using RxSwift
is a good decision in this case. Try making your chains more atomic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.