简体   繁体   English

RxSwift - 订阅方法

[英]RxSwift - subscribe to a method

Is there a way with RxSwift to subscribe to a method which returns a completion block? 有没有办法让RxSwift订阅一个返回完成块的方法?

Example, let's have this object: 例如,让我们有这个对象:

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)
        }
    }
}

And in a different place have a way to be notified when the service has been initialised: 并且在不同的地方有一种方法可以在服务初始化时得到通知:

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

service.init()

Would be there a simpler solution? 会有更简单的解决方案吗?

I like to use Variables for this sort of thing. 我喜欢使用Variables来做这类事情。 Also, I'd recommend using class here because you're tracking unique states and not just concerning yourself with values. 此外,我建议在这里使用课程,因为你正在追踪独特的状态,而不只是关注自己的价值观。

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.

You could use a lazy property: 你可以使用一个懒惰的属性:

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()
    }
}()

and then you can use: 然后你可以使用:

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

Let me know in the comments if you have problems before downvoting, thanks. 如果您在downvoting之前遇到问题,请在评论中告诉我们,谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM