2016-09-28 91 views
1

當我訂閱前添加toArray(),我沒有回調。RxSwift 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() 
    } 
} 

回答

3

使用debug()檢查,並確保你得到一個Completed事件(沒有toArray())。一旦源序列完成,toArray()將只發出Array

-1

那麼,如果它不共享(.share) 像

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) 
+1

這是不正確,你只能訂閱一次可觀察到的。你肯定**可以**不止一次訂閱一個'Observable'。每次訂閱時,您都會創建一個全新的序列,但這完全取決於您的需求。使用'share()'會給你一個單一的共享序列,根據你的需要,這也是有用的。它們都是可能的,但都可以用於不同的目的。 – solidcell

+0

我站好了 –