当我在订阅之前添加toArray()时,我没有得到回调。
googleCalendarUseCase.getEventsFromCalendars(calendars: selectedCalendars).subscribe(onNext: { (event) in
print(event.summary) //print thousands of elements
}).addDisposableTo(disposeBag)
googleCalendarUseCase.getEventsFromCalendars(calendars: selectedCalendars).toArray().subscribe(onNext: { (events) in
print(events.count) // Never gets called
}).addDisposableTo(disposeBag)
问题可能是函数getEventsFromCalendar,但不确定为什么它可以工作如果我不做toArray():
func getEventsFromCalendars(calendars: [GoogleCalendar.Calendar], nextPageToken: String? = nil) -> Observable<GoogleCalendar.Event> {
return Observable<GoogleCalendar.Event>.create { observer -> Disposable in
var parameters: [String: Any] = [:]
if let nextPageToken = nextPageToken {
parameters["pageToken"] = nextPageToken
}
_ = self.oauthswift.client.get(GoogleCalendarAPI.events, parameters: parameters, success: { (data, response) in
if let json = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
if let nextPageToken = self.nextPageToken(json: json) {
_ = Observable.of(Observable.from(self.getEventsFromJSON(json: json)), self.getEventsFromCalendars(calendars: calendars, nextPageToken: nextPageToken))
.merge().subscribe(observer)
} else {
_ = Observable.from(self.getEventsFromJSON(json: json))
}
} else {
observer.onError(CustomError.other)
}}, failure: { (error) in observer.onError(CustomError.noInet) }
)
return Disposables.create()
}
}
答案 0 :(得分:5)
使用debug()
检查并确保您收到Completed
个活动(没有toArray()
)。一旦源序列完成,toArray()
将仅发出Array
。
答案 1 :(得分:-1)
如果不共享(.share),你只能订阅一次observable 像
let sharedObservable = googleCalendarUseCase.getEventsFromCalendars(calendars: selectedCalendars).share()
sharedObservable.subscribe(onNext: { (event) in
print(event.summary)
}).addDisposableTo(disposeBag)
sharedObservable.toArray().subscribe(onNext: { (events) in
print(events.count)
}).addDisposableTo(disposeBag)