Observable life cycle
In the image above, 9 elements can be observed to be emitted. When an observable object emits an element, it emits it in the next event.
Observable
Issue three tap events and then end. This is called an completed
event.
The observable object emits error
an event containing an error. If an observable object emits an error
event, it will also terminate and cannot emit any other events.
An event that observable
emits the next
containing element.
Initialize the environment
Create a project named RXSwiftDemo, at the command line pod init
, the podfile
fill in the following and run pod install
.
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'RXSwiftDemo' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for RXSwiftDemo
pod 'RxSwift', '6.1.0'
pod 'RxCocoa', '6.1.0'
target 'RXSwiftDemoUITests' do
pod 'RxBlocking', '6.1.0'
pod 'RxTest', '6.1.0'
end
end
workspace
You can open it for actual combat.
Create observable
just
Name it aptly, because all it does is create an just
observable sequence of a single element.
The operator creates an observable instance of the individual type from a regular array of elements from
.
You can of
use it to create observable
an array or create a single type of observable array.
The following example can be distinguished just
, of
and from
.
let one = 1
let two = 2
let three = 3
/// This is a singe element observable
let observable: Observable<Int> = Observable<Int>.just(one)
/// This is an observable of individual type instances from a array
let observable2 = Observable.of(one, two, three)
/// This is an observables array using of to create
let observable3 = Observable.of([one, two, three])
/// This is an observable of individual type instances from a array
let observable4 = Observable.from([one, two, three])
Subscribe to observations subscribe
The observer is used to listen to the event, and then it needs this event to respond. For example: the pop-up prompt box is the observer, which responds to the event of clicking the button.
Subscribing RxSwift
to observables is very similar; you call observable subscribing.
Therefore addObserver()
, you can use instead subscribe()
.
Unlike NotificationCenter
developers who usually only use their .default
singleton instances, Rx
each observable instance in is different.
More importantly, observable
only subscribers can send events.
Examples of observable variables
let one = 1
let two = 2
let three = 3
/// This is an observable of individual type instances from a array
let observable = Observable.of(one, two, three)
/// Subscribes an element handler
observable.subscribe(onNext: {
element in
print(element) // Result will be: 1,2,3
})
/// Subscribes an event handler to an observable sequence.
observable.subscribe {
event in
print(event) // Result will be: next(1) next(2) next(3) completed
}
The empty
operator of creates an empty observable sequence with zero elements. It will only emit one .completed
event.
let observable = Observable<Void>.empty()
observable
.subscribe(
onNext: {
element in
print(element)
},
/// When empty an observable, it will go to completed block
onCompleted: {
print("Completed")
}
)
never
Create an observable in operation that does not emit anything and never terminates
/// If never an observable, it will not emit anything
let observable = Observable<Any>.never()
observable
.subscribe(
onNext: {
element in
print(element)
},
onCompleted: {
print("Completed")
}
)
Dispose and terminate dispose
To unsubscribe explicitly, call dispose()
it. After unsubscribing or unsubscribing, the dispose
current example observable
will stop emitting events
let observable = Observable.of("A", "B", "C")
let subscription = observable.subscribe {
event in
print(event)
}
/// When dispose, the observable can not emit anything
subscription.dispose()
It would be tedious to manage each subscription individually, so RxSwift
include a DisposeBag
type. The disposal bag can contain .disposed(by: disposeBag)
the disposable items that are usually added using this method, and dispose()
each disposal bag will be called when the disposal bag is about to be released.
let disposeBag = DisposeBag()
Observable.of("A", "B", "C")
.subscribe {
print($0)
}.disposed(by: disposeBag)
The create
operator has a parameter named subscribe
. Its job is to provide an implementation of observable call subscriptions.
Use create
custom observable
let disposeBag = DisposeBag()
Observable<String>.create {
(observer) -> Disposable in
observer.onNext("1")
observer.onNext("?")
return Disposables.create()
}.subscribe(
onNext: {
print($0) },
onError: {
print($0) },
onCompleted: {
print("Completed") })
.disposed(by: disposeBag)
Operator-Operator-Filter
Operators can help you create a new sequence, or change and combine the original sequence to generate a new sequence.
We have used operators many times in the input validation example before. For example, use the map method to convert the entered user name to whether the user name is valid. Then use this converted sequence to control whether the red prompt is hidden. We also use the combineLatest method to combine whether the user name is valid and whether the password is valid to be valid at the same time. Then use this synthesized sequence to control whether the button is clickable.
Here map and combineLatest are both operators, they can help us construct the required sequence. Now, let’s look at a few more examples:
filter-filter
let disposeBag = DisposeBag()
let rxTemperature: Observable<Double> = Observable.of(10.0, 11.0, 20.0, 35.0, 40.0)
rxTemperature.filter {
temperature in
temperature > 33
}.subscribe(onNext: {
temperature in
print("high temperature \(temperature)°")
}).disposed(by: disposeBag)
Build an observable factory
deferred
Delay reading the value until subscribed.
deferred
There is a feature to remember. Every time there is a new observer, it deferred
will be created from its closure Observable
. This means that subscribing 2 times will create 2 observables. It will affect performance, but it is unlikely that
deferred
it will help when subscribing to the long calculation function (if you use create
or, it will block just
)
let disposeBag = DisposeBag()
var flip = false
let factory: Observable<Int> = Observable.deferred {
() -> Observable<Int> in
flip = !flip
if flip {
return Observable.of(1, 2, 3)
} else {
return Observable.of(4, 5, 6)
}
}
for _ in 0...1 {
factory.subscribe(onNext: {
print($0, terminator: " ... ")
}).disposed(by: disposeBag)
print()
}
reference
https://medium.com/@duydtdev/observables-in-rxswift-f2f451df49b7
https://beeth0ven.github.io/RxSwift-Chinese-Documentation/content/rxswift_core/observable.html
https://github.com/ReactiveX/RxSwift