Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
Earl Grey Avatar asked Oct 15 '16 11:10

Earl Grey


2 Answers

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.

like image 124
Evghenii Nicolaev Avatar answered Oct 15 '22 01:10

Evghenii Nicolaev


In RxSwift Variable is deprecated. Use BehaviorRelay or BehaviorSubject

like image 30
user6902806 Avatar answered Oct 15 '22 00:10

user6902806