RxSwift - 订阅方法

时间:2017-02-20 19:48:45

标签: ios swift rx-swift

有没有办法让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()

会有更简单的解决方案吗?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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)

如果您在发表评论之前遇到问题,请在评论中告诉我们,谢谢。