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.
In RxSwift Variable
is deprecated. Use BehaviorRelay
or BehaviorSubject
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With