简体   繁体   中英

Creating an observable with RxSwift

I'm using RxSwift and I'm trying to extend another library I'm using to make something observable.

The library basically calls a delegate method every time a value changes, and I want to hook into this and whenever it calls the delegate, also add the new value to an observable sequence I want to create in my subclass.

I've seen how you can create observable sequences, but in each example next events are sent to the observer within the block given to the Observable.create method. I have no idea how I can add things to the observable sequence from "outside" this block passed to create .

I just want to create something that I can observe or can drive things with RxSwift, and manually add to the sequence at certain points.

I'd be very grateful if someone could point me in the right direction, as I'm very new to this.

Observable is readonly interface. Sequences created by Observable.create can only produce the value(s) given at construction time and nothing more. You can't "add things" to it, to use your words. Speaking in RxSwift terms, you can't do away with just Observable interface, you need also ObserverType - it must also observe your mutating value. There is more than one way to do it in RxSwift, but i think that you need PublishSubject :

let value = PublishSubject<YourType>()
let disposer = DisposeBag()

init() {
  value.subscribe(onNext: { (newValue) in 
    // use newValue ...
  }).addDisposableTo(disposer)
}

func yourDelegateHandler(newValue: YourType)
{
  value.onNext(newValue)      
}

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