RxSwift chapter
- first
- Sequential response logic
- Sequence types
- The operator
- Scheduler – Scheduler (1)
- Scheduler – Scheduler (2)
- Common sequence
- Subject is both offensive and defensive
- MVVM bidirectional binding
The following is from the official documentation
A: Transforming Observables
1.map
Definition: Transform the items emitted by an Observable by applying a function to each item
- The map pass-in function acts on the elements emitted by the observable sequence.
let mapOb = Observable.of(1, 2, 3)
mapOb.map { (number) -> Int in
return number * 2
}
.subscribe {
print($0)
}
.disposed(by: disposeBag)
Copy the code
2.flatMap
Emitted by an Observable into Observables then flatten the emissions from those into a single Observable
-
The FlatMap operator transforms an Observable that responds to subscriptions by applying a specified function to each entry emitted by the source Observable. That is, FlatMap merges Observable results and issues the combined results as its own sequence.
-
This approach is useful, for example, if a sequence has observable members or is otherwise converted to visible, so that a new observable can be created that emits a complete collection of items emitted by the children of those items.
struct PLPlayer {
let score: BehaviorSubject<Int>
init(score: Int) {
self.score = BehaviorSubject(value: score)
}
}
//flatMap
let boy = PLPlayer(score: 100)
let girl = PLPlayer(score: 90)
let player = BehaviorSubject(value: boy)
player.asObservable()
.flatMap { $0.score.asObservable() }
.subscribe(
onNext: { print($0) }
)
.disposed(by: disposeBag)
boy.score.onNext(60)
player.onNext(girl)
boy.score.onNext(50)
boy.score.onNext(40)
girl.score.onNext(10)
girl.score.onNext(0)
Copy the code
3.scan
Emitted by an Observable, sequentially, and emit each successive value
- Start with a default value, then apply an accumulator closure to each element emitted by the observable sequence and return each intermediate result as a single observable sequence of elements.
Observable.of(10, 100, 1000)
.scan(1) { aggregateValue, newValue in
aggregateValue + newValue
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
Copy the code
2: Filtering Observables
1.filter
Emit only those items from an Observable that pass a predicate test * Controls the sequence to emit only predicates.
Observable.of (1, 2, 3, 4, 5)
.filter { $0 % 2 == 0}
.subscribe { (event) in
print(event)
}
.disposed(by: disposeBag)
Copy the code
2.distinctUntilChanged
Definition: Suppress duplicate items emitted by an Observable
- Disallow sequences to emit repeated signals.
Observable.of("1"."2"."2"."3")
.distinctUntilChanged()
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
Copy the code
3.elementAt
Emitted only item n emitted by an Observable
- Extracts the item at the specified index position from the sequence of items emitted by the source observable and emits the item as its own unique emission.
Observable.of("1"."2"."3"."4")
.elementAt(2)
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
Copy the code
4.single
- Emit only the first element emitted by the observable sequence (or the first element that satisfies the condition). If the observable sequence emits more than one element, an error is thrown.
Observable.of("A"."B")
.single().subscribe { (event) in
print(event)
}
.disposed(by: disposeBag)
Observable.of("A"."B"."C")
.single { $0= ="B" }
.subscribe { (event) in
print(event)
}
.disposed(by: disposeBag)
Copy the code
5.take
Emitted only the first n items emitted by an Observable
- Commands an Observable to emit only the first n entries
Observable.of("A"."B"."C")
.take(2)
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
Copy the code
6.takeLast
Emitted only the final n items emitted by an Observable
- Controls an Observable to emit only the last n entries
Observable.of("A"."B"."C")
.takeLast(2).subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
Copy the code
7.takeWhile
Emitted mirror items emitted by an Observable until a specified condition becomes false
- As long as the value of the condition is specified as true, the elements are emitted from the beginning of the observable sequence until the condition false ends.
Observable.of (1, 2, 3, 4, 5)
.takeWhile { $0 < 3 }
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
Copy the code
8.takeUntil
Emitted by an Observable after a second Observable emits an item or terminates
- The sequence signals until the second observation object (referenceSequence) issues an item or terminates after the sequence ends.
let sourceSequence = PublishSubject<String>()
let referenceSequence = PublishSubject<String>()
sourceSequence
.takeUntil(referenceSequence)
.subscribe { print($0) }
.disposed(by: disposeBag)
sourceSequence.onNext("A")
sourceSequence.onNext("B")
referenceSequence.onNext("C"(// As soon as the conditions come out, the end of... There's no going down theresourceSequence.onNext("D")
sourceSequence.onNext("E")
Copy the code
9.skip
Definition: Suppress the first n items emitted by an Observable
- Disallow the first n items of a sequence
Observable.of(1, 2, 3, 4, 5, 6)
.skip(2)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
Copy the code
10.skipUntil
Emitted by an Observable until a second Observable emits an item
- Prevents the sequence from emitting an item until the second observation object (referenceSeq) emits an item.
let sourceSeq = PublishSubject<String>()
let referenceSeq = PublishSubject<String>()
sourceSeq
.skipUntil(referenceSeq)
.subscribe { print($0Disposed (by: disposeBag) // If the condition is not disposed, no moresourceSeq.onNext("A")
sourceSeq.onNext("B")
referenceSeq.onNext("C"(// As soon as the conditions come out, the end of... So let's do thatsourceSeq.onNext("D")
sourceSeq.onNext("E")
Copy the code
Three: Combining Observables
1.startWith
Emit a specified sequence of items before beginning to emit the items from the source Observable
- Emits the specified sequence of elements before starting to emit elements from the observable source
Observable.of("1"."2")
.startWith("A")
.startWith("a"."b")
.subscribe(onNext: {
print($0Disposed (by: disposeBagCopy the code
2.merge
2. Combine multiple Observables into one by merging their emissions
- Combine elements (sequences) from the source observable sequence into a new observable sequence and, after subscription, signal in response to each sequence.
let subject1 = PublishSubject<String>()
let subject2 = PublishSubject<String>()
Observable.of(subject1, subject2)
.merge()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
subject1.onNext("A")
subject2.onNext("B")
subject1.onNext("C"Result: any response to ABC triggers a new sequence response.Copy the code
3.zip
Definition: To combine the emissions of multiple observable items by a specified function and emit a single item for each combination based on the result of the function
- Combine the source observable sequence into a new observable sequence.
- The combination signal of the original sequence is processed from the new sequencing column, in which the elements of each source observable sequence are sequentially extracted. The number of combined signals is the same as the number of items emitted by the source observable that emits the fewest items.
- The function passed in by the new sequence acts on the combined signal, controlling the result of the final signal.
let stringSubject = PublishSubject<String>()
let intSubject = PublishSubject<Int>()
Observable.zip(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
stringSubject.onNext("A")
stringSubject.onNext("B") // A is stored here but will not respond (unless: another response); Intsubject.onnext (1) // check intsubject.onNext (2) // check another stringSubject.onNext("C"OnNext (3); // A 1 / B 2 // C 3; // B 2 // C 3Copy the code
4.combineLatest
Definition: When an item is emitted by one of two observables, the last item emitted by each observable is combined by the specified function and emitted based on the result of that function
- Combine the source observable sequence into a new observable sequence.
- The combination signal of the original sequence is processed in the new sequencing column, which is to extract the latest element of the observable sequence of each source sequentially, provided that at least one item is emitted from each source.
- The function passed in by the new sequence acts on the combined signal, controlling the result of the final signal.
let stringSub = PublishSubject<String>()
let intSub = PublishSubject<Int>()
Observable.combineLatest(stringSub, intSub) { strElement, intElement in
"\(strElement) \(intElement)"
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
stringSub.onNext("A") // Save A stringsub.onnext ("B"OnNext (2) // Override 1 -> 2 Find strOB has value B response B 2 stringSub.onNext("XY") // Overwrite B -> Cooci finds intOB has value 2 in response to XY 2 // prints the result: // B 1 // B 2 // XY 2Copy the code
5.switchLatest
Definition: Converts an observable that emits observations into a single observable that emits items emitted by the most recently emitted observables
let switchLatestSub1 = BehaviorSubject(value: "A")
let switchLatestSub2 = BehaviorSubject(value: "1")
letswitchLatestSub = BehaviorSubject(value: SwitchLatestSub1) / / chose switchLatestSub1 wouldn't listen switchLatestSub2 switchLatestSub. AsObservable () switchLatest () .subscribe(onNext: {print($0) })
.disposed(by: disposeBag)
switchLatestSub1.onNext("B")
switchLatestSub1.onNext("C")
switchLatestSub2.onNext("2")
switchLatestSub2.onNext("3"Switchlatestsub. onNext(switchLatestSub2) // Switch to switchLatestSub2 switchLatestSub1.onNext("D")
switchLatestSub1.onNext("XY"Switchlatestsub. onNext(switchLatestSub1) // Prints the result: // A // B // C // 3 // XYCopy the code
4: Mathematical and Aggregate Operators
1.reduce
Emitted by an Observable, sequentially, and emit the final value, apply a function to each item emitted by an Observable, sequentially, and emit the final value
- You start with the initialization value of a set, then apply the accumulator closure to all elements emitted by an observable sequence and return the aggregate result as a single observable sequence of elements
Observable.of(10, 100, 1000)
.reduce(1, accumulator: +)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
Copy the code
2.concat
Emit the emissions from two or more Observables without interleaving them
- Concatenate the outputs of multiple observation objects so that they behave like a single observation object, with all items issued by the first observation object preceding any items issued by the second observation object (and so on if there are more than two).
let subject1 = BehaviorSubject(value: "A")
let subject2 = BehaviorSubject(value: "1") / /let subjectsSubject = BehaviorSubject(value: subject1)
subjectsSubject.asObservable()
.concat()
.subscribe { print($0) }
.disposed(by: disposeBag)
subject1.onNext("B")
subject1.onNext("C"OnNext (Subject2) Subject2. OnNext (Subject2)"It won't print.")
subject2.onNext("2") subject1.onCompleted() // You must wait for Subject1 to complete before you can subscribe! subject2.onNext("3")
Copy the code
Five: To Convert Observables
Convert an Observable into another object or data structure
1.toArray
- Combine the source sequence signal into an array signal of the new sequence, the source sequence terminates, and the new sequence emits the array signal.
Observable.range(start: 1, count: 10)
.toArray()
.subscribe {
print($0)
}
.disposed(by: disposeBag)
Copy the code