This article is from My RxSwift Summary ①, My RxSwift Summary② It is a continuation.
ʻObservable, ʻobservable sequence
, sequence
, stream
These are all words that have the same meaning and are ** event flow **. (In RxSwift, sequence
is often used)
(Quote)
*** Everything is a sequence ***.
Events here include numbers, instances of classes defined by themselves, tap gestures, and so on.
This event is defined by the following ʻEnum`.
Event.swift
public enum Event<Element> {
case next(Element)
case error(Error)
case completed
}
What happens in each case
, ʻObservable (sequence)If you look at it with the marble diagram that shows below, ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/595260/cba274d6-319e-2902-494c-adc3ce7d3cf7.png) In the case of
next, ʻObservable
emits the next event. It also keeps emitting events until ʻerror / completed` is called.
In case of ʻerror, ʻError
is emitted, and ʻobservable` stops the emission of events.
In the case of completed
, ʻobservable` is stopped and the event is stopped.
ʻIn order to use the events emitted from Observable, you need to
subscribe. (ʻObservable
does not emit an event or process with ʻoperator until it is
Subscribe) At this time,
handlercan be added for each event type. Also, if it is
next, the error instance can be passed to
handler if it is ʻElement
, and if it is ʻerror`.
Consider the Observable shown in the marble diagram below
Example.swift
let one = "1"
let two = "2"
let three = "3"
let observable = Observable.of(one, two, three)
observable.subscribe { event in
print(event)
}
output
next(1)
next(2)
next(3)
completed
If you subscribe
, you will be able to handle events in sequence.
When you print
it, next
flows 3 times like the output, and finally completed
which means stop of ʻobservable` flows.
Recommended Posts