我有一个可观察到的列表,它们是从特定点请求Google距离和持续时间信息的请求。我试图仅在获取所有这些信息时才加载屏幕,但从未调用我对这些可观察对象的下一个订阅(调用了“ observer.onNext(viewModel)行,并且已获取信息),只有订阅(onNext)没有被调用)。我该如何等待直到这些可观察到的事物完成?
func stationInfoObservable(userLocation: CLLocationCoordinate2D, stations: [Station]) -> [Observable<GasStationTableCellViewModel>] {
var observables: [Observable<GasStationTableCellViewModel>] = []
for station in stations {
observables.append(Observable.create({ observer in
guard let toCoordinate = station.coordinate() else { return Disposables.create() }
self.mapDirections.routes(from: userLocation.asPlace(), to: toCoordinate.asPlace()) { routes, error in
if let error = error {
logger.error(error)
} else {
guard let leg = routes.first?.legs?.first else {
return
}
guard let distance = leg.distance?.text, let duration = leg.duration?.text else { return }
station.distanceInKMFromUserLocation = distance
station.distanceInMinutesFromUserLocation = duration
let viewModel = GasStationTableCellViewModel(station: station)
observer.onNext(viewModel)
observer.onCompleted()
}
}
return Disposables.create()
}))
}
return observables
}
我正在尝试以这种方式进行订阅(编辑:我现在正在尝试使用zip,但是驱动器/订阅仍未被调用):
Observable.zip(observables)
.asDriver(onErrorJustReturn: [])
.drive(onNext: { test in
print(test)
}, onCompleted: {
print("aa")
}).disposed(by: DisposeBag())
答案 0 :(得分:1)
根据您的订阅代码,您似乎没有保留DisposeBag
。您必须保留该对象,因为当它被释放时,它拥有的所有一次性物品都会被立即处置。尝试使其成为属性并使用该属性:
class MyClass {
let disposeBag = DisposeBag()
func setupSubscription() {
Observable.zip(observables)
.asDriver(onErrorJustReturn: [])
.drive(onNext: { test in
print(test)
}, onCompleted: {
print("aa")
}).disposed(by: disposeBag)
}
}