2016-04-01 19 views
9

Tôi có đoạn mã này:sáp nhập hai nhà quan sát thông báo trong RxSwift

let appActiveNotifications: [Observable<NSNotification>] = [ 
    NSNotificationCenter.defaultCenter().rx_notification(UIApplicationWillEnterForegroundNotification), 
    NSNotificationCenter.defaultCenter().rx_notification(Constants.AppRuntimeCallIncomingNotification) 
] 

appActiveNotifications.merge() 
    .takeUntil(self.rx_deallocated) 
    .subscribeNext() { [weak self] _ in 
    // notification handling 
} 
.addDisposableTo(disposeBag) 

Đó là nghĩa vụ phải lắng nghe một trong các thông báo cụ thể và xử lý khi ai trong số họ được kích hoạt.

Tuy nhiên điều này không biên dịch. Tôi nhận được lỗi sau:

Value of type '[Observable<NSNotification>]' has no member 'merge' 

Làm cách nào để hợp nhất hai tín hiệu này với một tín hiệu?

Trả lời

22

.merge() kết hợp nhiều Observables vì vậy bạn sẽ muốn làm appActiveNotifications.toObservable() sau đó gọi .merge() vào nó

Edit: Hoặc như ví dụ trong RxSwift's playground, bạn có thể sử dụng Observable.of() sau đó sử dụng .merge() vào nó; như vậy:

let a = NSNotificationCenter.defaultCenter().rx_notification(UIApplicationWillEnterForegroundNotification) 
let b = NSNotificationCenter.defaultCenter().rx_notification(Constants.AppRuntimeCallIncomingNotification) 

Observable.of(a, b) 
    .merge() 
    .takeUntil(self.rx_deallocated) 
    .subscribeNext() { [weak self] _ in 
    // notification handling 
    }.addDisposableTo(disposeBag) 
+0

Tôi muốn hợp nhất 2 loại Trình theo dõi khác nhau. Bất kỳ ý tưởng làm thế nào để đạt được? Đây là những gì tôi đang cố gắng làm. http://stackoverflow.com/questions/39050059/rxswift-merge-different-kind-of-observables –

+0

Bạn không thể hợp nhất 2 loại Đài quan sát khác nhau. Bạn phải chuyển đổi trên chúng hoặc cả hai để thực hiện một trận đấu! – nverinaud

+0

@SwiftHipster, bạn có thể sử dụng 'zip' để nhận cả hai kết quả và hợp nhất nó theo cách thủ công – Caipivara

Các vấn đề liên quan