2017-02-20 137 views
0

RxSwift是否有一種方法來訂閱返回完成塊的方法?RxSwift - 訂閱方法

例子,讓我們有這樣的對象:

struct Service { 

    private var otherService = ... 
    private var initSucceeded = PublishSubject<Bool>() 

    var initSucceededObservale: Observable<Bool> { 
     return initSucceeded.asObservable() 
    } 

    func init() { 
     otherService.init {(success) in 
      self.initSucceeded.onNext(success) 
     } 
    } 
} 

而且在不同的地方有當該服務已初始化通知的方式:

service.initSucceededObservable.subscribe(onNext: { 
    [unowned self] (value) in 
    ... 
}).addDisposableTo(disposeBag) 

service.init() 

將有一個簡單的解決方案?

回答

0

我喜歡用Variables來處理這類事情。另外,我建議在這裏使用課程,因爲你跟蹤的是獨特的狀態,而不僅僅是關注你自己的價值觀。

class Service { 
    private let bag = DisposeBag() 
    public var otherService: Service? 

    private var isInitializedVariable = Variable<Bool>(false) 

    public var isInitialized: Observable<Bool> { 
     return isInitializedVariable.asObservable() 
    } 

    public init(andRelyOn service: Service? = nil) { 
     otherService = service 

     otherService?.isInitialized 
      .subscribe(onNext: { [unowned self] value in 
       self.isInitializedVariable.value = value 
      }) 
      .addDisposableTo(bag) 
    } 

    public func initialize() { 
     isInitializedVariable.value = true 
    } 

} 

var otherService = Service() 
var dependentService = Service(andRelyOn: otherService) 

dependentService.isInitialized 
       .debug() 
       .subscribe({ 
        print($0) 
       }) 

otherService.initialize() // "Initializes" the first service, causing the second to set it's variable to true. 
0

你可以使用一個懶惰的屬性:

lazy let initSucceededObservale: Observable<Bool> = { 
    return Observable.create { observer in 
     self.otherService.init {(success) in 
      observer.on(.next(success)) 
      observer.on(.completed) 
     } 
     return Disposables.create() 
    } 
}() 

,然後你可以使用:

service.init() 
service.initSucceededObservable.subscribe(onNext: { 
    [unowned self] (value) in 
    ... 
}).addDisposableTo(disposeBag) 

讓我知道在評論,如果你有downvoting之前的問題,謝謝。