Earl Grey
Earl Grey

Reputation: 7466

How do I initialize an observable property in RxSwift?

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

enter image description here

How can I initialize the RxSwift observable to 5?

Upvotes: 9

Views: 16112

Answers (5)

Evghenii Nicolaev
Evghenii Nicolaev

Reputation: 584

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.

Upvotes: 15

user6902806
user6902806

Reputation: 280

In RxSwift Variable is deprecated. Use BehaviorRelay or BehaviorSubject

Upvotes: 2

Matthijs
Matthijs

Reputation: 535

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

Upvotes: 1

Maxim Volgin
Maxim Volgin

Reputation: 4077

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

Upvotes: 0

sfiss
sfiss

Reputation: 2319

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.

Upvotes: 1

Related Questions