Search code examples
swift3reactive-programmingdeferredrx-swiftrx-cocoa

Swift 3: Convert PromiseKit deferred to RxSwift


I'm currently replacing PromiseKit with RxSwift, and need to convert my deferred promise to RxSwift.

Current implementation example in PromiseKit:

private var deferredDidLayout = Promise<()>.pending()

override func layoutSubviews() {
    super.layoutSubviews()

    self.deferredDidLayout.fulfill()
}

func setup() {
    _ = self.didLayout().then {_ -> Void in
        // Do my stuff only one time!
    }
}

private func didLayout() -> Promise<()> {
    return self.deferredDidLayout.promise
}

Current hack-implementation in RxSwift:

private let observableDidLayout = PublishSubject<Void>()

override func layoutSubviews() {
    super.layoutSubviews()

    self.observableDidLayout.onCompleted()
}

func setup() {
     _ = self.observableDidLayout
        .subscribe(onCompleted: { _ in
            // Do my stuff only one time!
            // Issue: Will be executed on every onCompleted() call
     })
}

Thank you in regard!

PromiseKit: https://github.com/mxcl/PromiseKit RxSwift: https://github.com/ReactiveX/RxSwift


Solution

  • I believe that 'Completable' is what you are looking for - https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md#creating-a-completable