preface
From what I’ve learned about RxSwift, the documentation and instructions say that Observable is the very core part of Rx.
However, it is not easy to understand precisely because of its core and key. Programming is a very abstract thing, and it is difficult to sort out the knowledge points in the abstract.
Recently, I attended a training class of the company. I said that the real big guy can always explain very profound problems and concepts in a simple and easy to understand way.
I’ve been thinking about Observable, how to explain it to you, eating and sleeping.
Here is my understanding.
Explain the word Observable first
Notice that it’s an adjective meaning observable.
An Observable, or Observable, sequence.
Because the name is so long that it is often difficult to read, it is abbreviated to: Sequence when necessary.
Sequence, is that a familiar word? The English word is sequence. Yes, there is a Sequence protocol in Swift.
A Sequence is a set of values of the same type, and provides the ability to iterate over these values. The most common way to iterate over a Sequence is with a for-in, and provides the ability to iterate over these values.
You’re probably familiar with this code:
for element in someSequence {
print(element)
}
Copy the code
For-in is a kind of syntactic sugar. As long as a class or struct complies with Sequence protocol, it can perform the syntactic iteration. More importantly, it is the IteratorProtocol protocol in Sequence protocol that can traverse to the next element.
From Observable to Sequence, and then to Sequence protocol.
This is normal because Sequence protocol and IteratorProtocol are very abstract and not easy to understand. However, we are very familiar with the type of Sequence protocol, Array.
Let’s understand Observable by comparing it to Array.
Array and observables
Let’s start with a forEach traversal of an array:
let array = [0, 1, 2, 3, 4, 5]
array.forEach { element in
print(element)
}
Copy the code
The printed results are also very familiar:
0, 1, 2, 3, 4, 5Copy the code
Then we can generate an Observable to do the same thing.
let element = [0, 1, 2, 3, 4, 5]
let observable = Observable.from(element)
observable.subscribe { event in
print(event)
}.dispose()
Copy the code
When you’re using an Observable, it’s much easier to convert other types directly to An Observable. The FROM operator provides this functionality.
We generate an Observable with the from method and subscribe to try to print the information.
The result is this:
next(0)
next(1)
next(2)
next(3)
next(4)
next(5)
completed
Copy the code
Note that there are many subscribe functions with the same name. Here we use the red one:
It prints out each element of the array and has the last completed signal.
Let’s see what an Event
is:
/// Represents a sequence event.
///
/// Sequence grammar:
/// ****next\* (error | completed)** **
public enum Event<Element> {
/// Next element is produced.
case next(Element)
/// Sequence terminated with an error.
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
extension Event: CustomDebugStringConvertible {
/// Description of event.
public var debugDescription: String {
switch self {
case .next(let value):
return "next(\(value))"
case .error(let error):
return "error(\(error))"
case .completed:
return "completed"
}
}
}
Copy the code
An Event is essentially an enumeration with parameters that can represent an Observable (sequence) Event. Here, each element of [0, 1, 2, 3, 4, 5] is emitted as an event.
Please recall the Result type and Optional type in Swift. Are they familiar?
Check out my previous post: Swift: Enum, Will you use it?
Let’s refine the method in this subscribe:
observable.subscribe { (event: Event<Int>) in
switch event {
case .next(let some):
print(some)
case .error(let error):
print(error)
case .completed:
print(event.debugDescription)
}
}
Copy the code
The print results are more detailed:
0
1
2
3
4
5
completed
Copy the code
Some is the actual value that an Observable wants to pass. In this case, it represents an element in an array. We switch the enumeration to get the value and process it.
Let’s try to compare the two methods array.forEach and Observable. subscribe. They both do data processing for the elements in them.
In Rx, the subscribe function refers to the operation of subscribing to the observable sequence. In other words, the behavior of each element in the sequence can be understood and the operation can be performed.
The equivalence of observer pattern (Observable sequence) and normal sequences (Sequence) is the most important thing to understand about Rx.
Understanding the equivalence between Observable sequences and normal sequences is the most important thing to understand Rx.
conclusion
-
The types that comply with the Sequence protocol can be used to describe the sequences produced by synchronization.
-
An Observable can be used to describe a sequence of elements produced asynchronously, as well as synchronously.
single items | multiple item | |
---|---|---|
synchronous | T getData() |
Iterable<T> getData() |
asynchronous | Future<T> getData() |
Observable<T> getData() |
Hard to understand? In this case, you can think of an Observable as a special array in which each element can be an asynchronous callback.
An Array calls each element using forEach, while an Observable converts an asynchronous callback into a synchronous callback using subscribe in its method, and then processes the data and logic.
We’ll see that in the next video
Still don’t get it? Okay, in the next video, I’m going to give you a different way of thinking about Observable.
Hope to open a new window into your understanding of Observable.
Also note
The name of Observable (Observable) is too long, which makes it difficult to read in many cases. Therefore, I shorten it to “Sequence” when necessary.
Reference documentation
Observable – a sequence that can be listened to
RxSwift/Documentation/GettingStarted.md
ReactiveX/Introduction
RxSwift writes wanAndroid client now open source
RxSwift is now open-source to write wanAndroid clientsProject link.
I have adapted iOS dark mode and done a round of CodeReview, remember to give a star!
Attach an image of the effect: