简体   繁体   中英

How do I initialize an observable property in RxSwift?

I find this very puzzling. Coming from ReactiveCocoa I would expect something like this possible.

在此输入图像描述

How can I initialize the RxSwift observable to 5?

You can create stream in multiple ways:

Main way

    Observable<Int>.create { observer -> Disposable in

        // Send events through observer
        observer.onNext(3)
        observer.onError(NSError(domain: "", code: 1, userInfo: nil))
        observer.onCompleted()

        return Disposables.create {
            // Clean up when stream is deallocated
        }
    }

Shortcuts

    Observable<Int>.empty() // Completes straight away
    Observable<Int>.never() // Never gets any event into the stream, waits forever
    Observable<Int>.just(1) // Emit value "1" and completes

Through Subjects (aka Property / MutableProperty in ReactiveSwift)

Variable is deprecated in RxSwift 4, but it's just a wrapper around BehaviourSubject, so you can use it instead.

There are 2 most used subjects

BehaviorSubject - it will emit current value and upcoming ones. Because it will emit current value it needs to be initialised with a value BehaviorSubject<Int>(value: 0)

PublishSubject - it will emit upcoming values. It doesn't require initial value while initialising PublishSubject<Int>()

Then you can call .asObservable() on subject instance to get an observable.

I am not able to test it right now, but wouldn't Observable.just be the function you are looking for?

Source for Observable creation: github link

Of course, you could also use a Variable(5) if you intend to modify it.

As I am learning RxSwift I ran up on this thread. You can initialize an observable property like this:

var age = Variable<Int>(5)

And set it up as an observable:

let disposeBag = DisposeBag()

private func setupAgeObserver() {
    age.asObservable()
      .subscribe(onNext: {
        years in
        print ("age is \(years)")
        // do something
      })
      .addDisposableTo(disposeBag)
 }

In RxSwift Variable is deprecated. Use BehaviorRelay or BehaviorSubject

in Rx in general, there is a BehaviorSubject which stores the last value

specifically in RxSwift, there is also Variable which is a wrapper around BehaviorSubject

see description of both here - https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md

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