简体   繁体   中英

RxSwift - subscribe to a method

Is there a way with RxSwift to subscribe to a method which returns a completion block?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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