RxSwift练习demo(官方案例翻译)

2023-02-07  本文已影响0人  sws1314

RxSwift练习demo(官方案例翻译):

import UIKit
import RxSwift
import Swift

public enum TestError: Swift.Error {
    case test
}


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //支持多点触摸
        self.view.isMultipleTouchEnabled =  true
        
        
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(test))
        tap.cancelsTouchesInView = false
        view?.addGestureRecognizer(tap)
    }
    
    
    
    @objc func test() {
        //MARK: - of
//        Observable.of("❤️", "💟", "♉️")
//            .subscribe(onNext: {
//                print($0)
//            }).disposed(by: DisposeBag())
        /**
         输出:
         ❤️
         💟
         ♉️
         */
        
        
        //MARK: - from
//        Observable.from(["shi", "wen", "song"]).subscribe(onNext: { element in
//            print(element)
//        }).disposed(by: DisposeBag())
//
//        let disposeBag = DisposeBag()
//        let myJust = { (element: String) -> Observable<String> in
//            return Observable.create { observer in
//                observer.on(.next(element))
//                observer.on(.completed)
//                return Disposables.create()
//            }
//        }
//
//        myJust("sws").subscribe{
//            print($0)
//        }.disposed(by: disposeBag)
        /**
         输出:
         shi
         wen
         song
         next(sws)
         completed
         */
        
        
        //MARK: - range
//        Observable.range(start: 1, count: 20).subscribe{
//            print($0)
//        }.disposed(by: DisposeBag())
        /**
         输出:
         next(1)
         next(2)
         next(3)
         next(4)
         next(5)
         next(6)
         next(7)
         next(8)
         next(9)
         next(10)
         next(11)
         next(12)
         next(13)
         next(14)
         next(15)
         next(16)
         next(17)
         next(18)
         next(19)
         next(20)
         completed

         */

        
        //MARK: - repeatElement
//        Observable.repeatElement("sws")
//            .take(10)
//            .subscribe(onNext: {
//                print($0)
//            })
//            .disposed(by: DisposeBag())
        
        /*输出:
         sws
         sws
         sws
         sws
         sws
         sws
         sws
         sws
         sws
         sws
         */
        
        
        
        //MARK: - generate

//        Observable.generate(initialState: 0) { ele in
//            return ele < 30
//        } iterate: { el in
//            return el + 1
//        }.subscribe(onNext: { print($0)})
//            .disposed(by: DisposeBag())
        /*输出:
         0
         1
         2
         3
         4
         5
         6
         7
         8
         9
         10
         11
         12
         13
         14
         15
         16
         17
         18
         19
         20
         21
         22
         23
         24
         25
         26
         27
         28
         29
         */
        
        
        //MARK: - generate(condition:)

//        Observable.generate(initialState: 1, condition: { $0 < 10}, iterate: { $0 + 1 }).subscribe(onNext: {
//            print($0)
//        }).disposed(by: DisposeBag())
        /**
         输出:
         1
         2
         3
         4
         5
         6
         7
         8
         9
         */
        
        
        //MARK: - deferred
//        let disposeBag = DisposeBag()
//        var count = 1
//        let deferredSeq = Observable.deferred{
//            print("Creating \(count)")
//            count += 1
//            return Observable.create{ observer in
//                print("Emiting...")
//                observer.onNext("1")
//                observer.onNext("2")
//                observer.onNext("3")
//                return Disposables.create()
//            }
//        }
//
//        deferredSeq.subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        deferredSeq.subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出:
         Creating 1
         Emiting...
         1
         2
         3
         Creating 2
         Emiting...
         1
         2
         3
         */
        
        
        //MARK: - create
//        Observable.create { observer in
//            observer.onNext("sws")
//            return Disposables.create()
//        }.subscribe(onNext: { print($0) })
//
//
//        //MARK: - of
//        let obs = Observable.of("sws", "xuebing")
//        obs.subscribe(onNext: {
//            print("订阅者1: \($0)")
//        })
//        .disposed(by: DisposeBag())
//
//        obs.subscribe{
//            print("订阅者2: \($0)")
//        }
//        .disposed(by: DisposeBag())
        
        //MARK: - error
//        Observable.error(TestError.test)
//            .subscribe{ print($0)}
//            .disposed(by: DisposeBag())

        //MARK: - do
//        Observable.of("shi", "wen", "song")
//            .do(onNext: {print("Intercepted", $0)}, afterNext: {print("Intercepted after: ", $0)}, onError: {print("Intercepted error: ", $0)}, afterError: { print("Intercepted after error: ", $0)}, onCompleted: { print("Completed")}, afterCompleted:{ print("After completed")})
//                .subscribe(onNext: {print($0)})
//                .disposed(by: DisposeBag())
        /*
         输出:
         Intercepted shi
         shi
         Intercepted after:  shi
         Intercepted wen
         wen
         Intercepted after:  wen
         Intercepted song
         song
         Intercepted after:  song
         Completed
         After completed

         */
                
                
        //MARK: - PublishSubject
//        let disposeBag = DisposeBag()
//        let subject = PublishSubject<String>()
//        subject.addObserver("1").disposed(by: disposeBag)
//        subject.onNext("sws")
//        subject.onNext("wen")
//        subject.onNext("song")
//
//
//        subject.addObserver("2").disposed(by: disposeBag)
//        subject.onNext("A")
//        subject.onNext("B")
        
        /**
         输出:
         Subscription:  1 Event:  next(sws)
         Subscription:  1 Event:  next(wen)
         Subscription:  1 Event:  next(song)
         Subscription:  1 Event:  next(A)
         Subscription:  2 Event:  next(A)
         Subscription:  1 Event:  next(B)
         Subscription:  2 Event:  next(B)
         */
        
        
        //MARK: - ReplaySubject
//        let disposeBag = DisposeBag()
//        let subject = ReplaySubject<String>.create(bufferSize: 2)
//
//        subject.addObserver("1").disposed(by: disposeBag)
//        subject.onNext("sws")
//        subject.onNext("xuebing")
//
//        subject.addObserver("2").disposed(by: disposeBag)
//        subject.onNext("A")
//        subject.onNext("B")
        /**
         输出:
         Subscription:  1 Event:  next(sws)
         Subscription:  1 Event:  next(xuebing)
         Subscription:  2 Event:  next(sws)
         Subscription:  2 Event:  next(xuebing)
         Subscription:  1 Event:  next(A)
         Subscription:  2 Event:  next(A)
         Subscription:  1 Event:  next(B)
         Subscription:  2 Event:  next(B)
         */
        
        
        //MARK: - BehaviorSubject
//        let disposeBag = DisposeBag()
//        let subject = BehaviorSubject(value: "🔴")
//
//        subject.addObserver("1").disposed(by: disposeBag)
//        subject.onNext("🐶")
//        subject.onNext("🐱")
//
//        subject.addObserver("2").disposed(by: disposeBag)
//        subject.onNext("🅰️")
//        subject.onNext("🅱️")
//
//        subject.addObserver("3").disposed(by: disposeBag)
//        subject.onNext("🍐")
//        subject.onNext("🍊")
        
        /**
         输出:
         Subscription:  1 Event:  next(🔴)
         Subscription:  1 Event:  next(🐶)
         Subscription:  1 Event:  next(🐱)
         Subscription:  2 Event:  next(🐱)
         Subscription:  1 Event:  next(🅰️)
         Subscription:  2 Event:  next(🅰️)
         Subscription:  1 Event:  next(🅱️)
         Subscription:  2 Event:  next(🅱️)
         Subscription:  3 Event:  next(🅱️)
         Subscription:  1 Event:  next(🍐)
         Subscription:  2 Event:  next(🍐)
         Subscription:  3 Event:  next(🍐)
         Subscription:  1 Event:  next(🍊)
         Subscription:  2 Event:  next(🍊)
         Subscription:  3 Event:  next(🍊)

         */

        
            
        //MARK: - startWith
//        let disposeBag = DisposeBag()
//        Observable.of("🐶", "🐱", "🐭", "🐹")
//            .startWith("1️⃣")
//            .startWith("2️⃣")
//            .startWith("3️⃣", "🅰️", "🅱️")
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出:
         3️⃣
         🅰️
         🅱️
         2️⃣
         1️⃣
         🐶
         🐱
         🐭
         🐹

         */

        
//        //MARK: - merge
//        let disposeBag = DisposeBag()
//
//        let subject1 = PublishSubject<String>()
//        let subject2 = PublishSubject<String>()
//
//        Observable.of(subject1, subject2)
//            .merge()
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        subject1.onNext("🅰️")
//
//        subject1.onNext("🅱️")
//
//        subject2.onNext("①")
//
//        subject2.onNext("②")
//
//        subject1.onNext("🆎")
//
//        subject2.onNext("③")
        
        /**
         输出:
         🅰️
         🅱️
         ①
         ②
         🆎
         ③

         */
        
        //MARK: - zip
//        let disposeBag = DisposeBag()
//        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")
//
//        intSubject.onNext(1)
//        intSubject.onNext(2)
//
//        stringSubject.onNext("AB")
//        intSubject.onNext(3)
    /**
     输出结果:
         A 1
         B 2
         AB 3
     */

        
        
        //MARK: - combineLatest
        /**
         介绍: 将多达8个源可观察对象序列组合成一个新的可观察对象序列。一旦所有源序列都发出了至少一个元素,以及任何一个源可观察对象序列发出了一个新元素,就会从组合后的可观察对象序列中发出每个源可观察对象序列的最新元素。
         */
//        let disposeBag = DisposeBag()
//
//        let stringSubject = PublishSubject<String>()
//        let intSubject = PublishSubject<Int>()
//
//        Observable.combineLatest(stringSubject, intSubject) { stringElement, intElement in
//                "\(stringElement) \(intElement)"
//            }
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        stringSubject.onNext("🅰️")
//
//        stringSubject.onNext("🅱️")
//        intSubject.onNext(1)
//
//        intSubject.onNext(2)
//
//        stringSubject.onNext("🆎")
        /**
         输出结果:
             🅱️ 1
             🅱️ 2
             🆎 2
         */
        
        
        //MARK: - Array.combineLatest
        /**
         介绍: 因为combineLatest变体接受一个集合作为参数,并将一个数组传递给选择器函数,所以它要求所有源可观察序列的类型都是相同的。
         */
//        let disposeBag = DisposeBag()
//
//        let stringObservable = Observable.just("❤️")
//        let fruitObservable = Observable.from(["🍎", "🍐", "🍊"])
//        let animalObservable = Observable.of("🐶", "🐱", "🐭", "🐹")
//
//        Observable.combineLatest([stringObservable, fruitObservable, animalObservable]) {
//                return "\($0[0]) \($0[1]) \($0[2])"
//            }
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出结果:
         ❤️ 🍎 🐶
         ❤️ 🍐 🐶
         ❤️ 🍐 🐱
         ❤️ 🍊 🐱
         ❤️ 🍊 🐭
         ❤️ 🍊 🐹
         */
        
        
        //MARK: - switchLatest
        /**
         介绍: 将可观察序列发出的元素转换为可观察序列,并从最近的内部可观察序列发出元素。
         */
//        let disposeBag = DisposeBag()
//
//        let subject1 = BehaviorSubject(value: "🐢")
//        let subject2 = BehaviorSubject(value: "🐯")
//
//        let subjectsSubject = BehaviorSubject(value: subject1)
//
//        subjectsSubject.asObservable()
//            .switchLatest()
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        subject1.onNext("🌼")
//        subject1.onNext("🌸")
//
//        subjectsSubject.onNext(subject2)
//
//        subject1.onNext("A") // 这个不会输出, 因为现在已经切换到了subject2
//        subject2.onNext("B")
        
        /**
         输出结果:
         🐢
         🌼
         🌸
         🐯
         B
         */
        
        
        //MARK: - withLatestFrom
        /**
         将两个可观察序列合并为一个可观察序列,将第一个源的每个元素与第二个源的最新元素合并(如果有的话)。
         */
//        let disposeBag = DisposeBag()
//
//        let foodSubject = PublishSubject<String>()
//        let drinksSubject = PublishSubject<String>()
//
//        foodSubject.asObservable()
//            .withLatestFrom(drinksSubject) { "\($0) + \($1)" }
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        foodSubject.onNext("🥗")
//
//        drinksSubject.onNext("☕️")
//        foodSubject.onNext("🥐")
//
//        drinksSubject.onNext("🍷")
//        foodSubject.onNext("🍔")
//
//        foodSubject.onNext("🍟")
//
//        drinksSubject.onNext("🍾")
        /**
         输出结果:
         
         🥐 + ☕️
         🍔 + 🍷
         🍟 + 🍷
         */
        
        
        //MARK: - map
//        let disposeBag = DisposeBag()
//
//        Observable.of(1, 2, 3)
//            .map{ $0 * $0}
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
            
            /**
             输出结果:
             1
             4
             9
            */
        
        
        //MARK: - flatMap and flatMapLatest
        /**
         介绍: 将可观察序列发出的元素转换为可观察序列,并将两个可观察序列发出的元素合并为一个可观察序列。例如,当你有一个自身发出可观察序列的可观察序列,并且你希望能够对任何一个可观察序列的新发射做出反应时,这也很有用。flatMap和flatMapLatest的区别在于,flatMapLatest只会发出最近的内部可观察序列中的元素。
         */
//        let disposeBag = DisposeBag()
//        struct Player {
//
//            let score: BehaviorSubject<Int>
//
//            init(score: Int) {
//                self.score = BehaviorSubject(value: score)
//            }
//        }
//
//        let p1 = Player(score: 80)
//        let p2 = Player(score: 90)
//
//        let player = BehaviorSubject(value: p1)
//
//        player.asObservable()
//            .flatMap{ $0.score.asObservable() }
////            .flatMapLatest{ $0.score.asObservable() }
//            .subscribe(onNext: { print($0)})
//            .disposed(by: disposeBag)
//
//        p1.score.onNext(85)
//
//        player.onNext(p2)
//
//        p1.score.onNext(95)
//
//        p2.score.onNext(100)

        /**
         flatMap输出结果:
         80
         85
         90
         95
         100
         
         
         flatMapLastest输出结果:
         80
         85
         90
         100
         */
        
        //MARK: - scan
        /**
         介绍:
         从一个初始种子值开始,然后对可观察序列发出的每个元素应用一个accumulator闭包,并以单元素可观察序列的形式返回每个中间结果。
         */
//        let disposeBag = DisposeBag()
//
//        Observable.of(10, 100, 1000)
//            .scan(1){
//                aggregateValue, newValue in
//                aggregateValue + newValue
//            }
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
            /**
             11
             111
             1111
             */
        
        //MARK: - filter
//        let disposeBag = DisposeBag()
//
//        Observable.of(
//            "🐱", "🐰", "🐶",
//            "🐸", "🐱", "🐰",
//            "🐹", "🐸", "🐱")
//        .filter{
//            $0 == "🐱"
//        }.subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出结果:
         
         🐱
         🐱
         🐱
         */
        
        //MARK: - distinctUntilChanged
//        let disposeBag = DisposeBag()
//
//        Observable.of("🐱", "🐷", "🐱", "🐱", "🐱", "🐵", "🐱")
//            .distinctUntilChanged()
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出结果:
         
         🐱
         🐷
         🐱
         🐵
         🐱
         */
        
        //MARK: - elementAt
//        let disposeBag = DisposeBag()
//
//        Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
//            .element(at: 3)
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /*
         输出结果:
         🐸
         */
        
        
        //MARK: - single
        /*
         介绍: 只发出可观察序列发出的第一个元素(或满足条件的第一个元素)。如果Observable序列没有发出一个元素,就会抛出错误。
         */
        
//        let disposeBag = DisposeBag()
//
//        Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
//            .single()
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出结果:
         🐱
         Unhandled error happened: Sequence contains more than one element.
         */
        
        
//        let disposeBag = DisposeBag()
//
//        Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
//            .single { $0 == "🐸" }
//            .subscribe (onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        Observable.of("🐱", "🐰", "🐶", "🐱", "🐰", "🐶")
//            .single { $0 == "🐰" }
//            .subscribe (onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
//            .single { $0 == "🔵" }
//            .subscribe (onNext: { print($0) })
//            .disposed(by: disposeBag)
        
        /*
         输出结果:
         🐸
         🐰
         Unhandled error happened: Sequence contains more than one element.
         Unhandled error happened: Sequence doesn't contain any elements.
         */
        
        //MARK: - take
        /**
         介绍: 从可观察序列的开始只发出指定数量的元素
         */
//        let disposeBag = DisposeBag()
//        Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
//            .take(3)
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出结果:
         🐱
         🐰
         🐶
         */
        
        //MARK: - takeLast
        /**
         介绍: 只从可观察序列的末尾发出指定数量的元素。
         */
//        let disposeBag = DisposeBag()
//
//        Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
//            .takeLast(3)
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        
        /**
         输出结果:
         🐸
         🐷
         🐵
         */
        
        
        //MARK: - takeWhile
        /**
         从可观察序列的开始发出元素,只要指定的条件求值为true。
        */
        
//        let disposeBag = DisposeBag()
//
//        Observable.of(1, 2, 3, 4, 5, 6)
//            .take(while: { $0 < 4 })
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出结果:
         1
         2
         3
         */
        
        
        //MARK: - takeUntil
        /**
         介绍:
         从源可观察序列中发出元素,直到引用可观察序列发出一个元素。
         */
        
//        let disposeBag = DisposeBag()
//
//        let sourceSequence = PublishSubject<String>()
//        let referenceSequence = PublishSubject<String>()
//
//        sourceSequence
//            .takeUntil(referenceSequence)
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        sourceSequence.onNext("🐱")
//        sourceSequence.onNext("🐰")
//        sourceSequence.onNext("🐶")
//
//        referenceSequence.onNext("🔴")
//
//        sourceSequence.onNext("🐸")
//        sourceSequence.onNext("🐷")
//        sourceSequence.onNext("🐵")
        
        /**
         结果输出:
         🐱
         🐰
         🐶
         */
        
        
        //MARK: - skip
        /**
         介绍:
         禁止从可观察序列开始发出指定数量的元素。
         */
//        let disposeBag = DisposeBag()
//
//        Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
//            .skip(2)
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
            
        /**
         输出结果:
         🐶
         🐸
         🐷
         🐵
         */
        
        
        //MARK: - skipWhile
        /**
         介绍:
         禁止从可观察对象序列的开始发出满足指定条件的元素。
         */
//        let disposeBag = DisposeBag()
//
//        Observable.of(1, 2, 3, 4, 5, 6)
//            .skip(while: { $0 < 4 })
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        
        /**
         输出结果:
         4
         5
         6
         */
        
        //MARK: - skipWhileWithIndex
        /**
         介绍:
         禁止发射从可观察序列开始的满足指定条件的元素,并发射剩余的元素。闭包还会传递每个元素的索引。
         */
//        let disposeBag = DisposeBag()
//
//        Observable.of("🐱", "🐰", "🐶", "🐸", "🐷", "🐵")
//            .enumerated()
//            .skip(while: { $0.index < 3 })
//            .map{ $0.element }
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
            
        /**
         输出结果:
         🐸
         🐷
         🐵
         */
        
        
        //MARK: - skipUntil
        /**
         介绍:
         禁止从源可观察序列中发出元素,直到引用可观察序列发出一个元素。
         */
//        let disposeBag = DisposeBag()
//
//        let sourceSequence = PublishSubject<String>()
//        let referenceSequence = PublishSubject<String>()
//
//        sourceSequence.skip(until: referenceSequence)
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        sourceSequence.onNext("🐱")
//        sourceSequence.onNext("🐰")
//        sourceSequence.onNext("🐶")
//
//        referenceSequence.onNext("🔴")
//
//        sourceSequence.onNext("🐸")
//        sourceSequence.onNext("🐷")
//        sourceSequence.onNext("🐵")

        /**
         输出结果:
         🐸
         🐷
         🐵
         */
        
        //MARK: - toArray
        /**
         介绍:
         将一个可观察序列转换为一个数组,将该数组作为一个新的单元素可观察序列发出,然后终止。
         */
//        let disposeBag = DisposeBag()
//
//        Observable.range(start: 1, count: 10)
//            .toArray()
//            .subscribe({
//                print($0)
//                print(type(of: $0))
//            })
//            .disposed(by: disposeBag)
        
        /**
         输出结果:
         success([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
         Result<Array<Int>, Error>
         */
        
        
        //MARK: - reduce
        /**
         介绍:
         从一个初始的种子值开始,然后对一个可观察序列发出的所有元素应用一个累加器闭包,并以单元素可观察序列的形式返回聚合结果。
         */
//        let disposeBag = DisposeBag()
//
//        Observable.of(10, 100, 1000)
//            .reduce(1, accumulator: +)
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        /**
         输出结果:
         1111
         */
        
        
        //MARK: - concat
        /**
         介绍:
         以顺序的方式从一个可观察序列的内部可观察序列中连接元素,等待每个序列成功结束,然后从下一个序列中发射元素。
         */
//        let disposeBag = DisposeBag()
//
//        let subject1 = BehaviorSubject(value: "🍎")
//        let subject2 = BehaviorSubject(value: "🐶")
//
//        let subjectsSubject = BehaviorSubject(value: subject1)
//
//        subjectsSubject.asObserver()
//            .concat()
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        subject1.onNext("🍐")
//        subject1.onNext("🍊")
//
//        subjectsSubject.onNext(subject2)
//
//        subject2.onNext("I would be ignored")
//        subject2.onNext("🐱")
//
//        subject1.onCompleted()
//
//        subject2.onNext("🐭")
        /**
         输出结果:
         🍎
         🍐
         🍊
         🐱
         🐭

         */
        
        
        //MARK: - Connectable Operators
        /**
         介绍:
         可连接的可观察序列类似于普通的可观察序列,除了它们在被订阅时不会开始发出元素,而是只有在它们的connect()方法被调用时才开始发出元素。通过这种方式,你可以等待所有预定的订阅者在开始发出元素之前订阅一个可连接的可观察对象序列。
         
         注:
         在这个页面的每个示例中都有一个注释掉的方法。取消注释该方法以运行示例,然后再次注释它以停止运行示例。
         
         */
        
        //    在学习可连接运算符之前,让我们看一个不可连接运算符的例子:
//        let interval = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
//        _ = interval.subscribe(onNext: { print("Subscription: 1, Event: \($0)") })
//
//        delay(5){
//            _ = interval.subscribe(onNext: {
//                print("Subscription: 2, Event: \($0)")
//            })
//        }

        /*
         注: interval创建一个可观察序列,在每个周期之后,在指定的调度器上发出元素。
         */
        
        /**
         输出结果:
         Subscription: 1, Event: 0
         Subscription: 1, Event: 1
         Subscription: 1, Event: 2
         Subscription: 1, Event: 3
         Subscription: 1, Event: 4
         Subscription: 1, Event: 5
         Subscription: 2, Event: 0
         Subscription: 1, Event: 6
         Subscription: 2, Event: 1
         Subscription: 1, Event: 7
         Subscription: 2, Event: 2
         Subscription: 1, Event: 8
         Subscription: 2, Event: 3
         Subscription: 1, Event: 9
         Subscription: 2, Event: 4
         */
        
        
        //MARK: - publish
        /**
         介绍:
         将源可观察序列转换为可连接序列。
         */
//        let intSequence = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
//            .publish()
//
//        _ = intSequence.subscribe(onNext: { print("Subscription 1:, Event: \($0)") })
//
//        delay(2){
//            _ = intSequence.connect()
//        }
//
//        delay(4){
//            _ = intSequence.subscribe(onNext: {
//                print("Subscription 2:, Event: \($0)")
//            })
//        }
//
//        delay(6){
//            _ = intSequence.subscribe(onNext: { print("Subscription 3:, Event: \($0)") })
//        }
        
        /**
         注: 调度器是对执行工作的机制的抽象,例如在特定的线程或分派队列上。
         */
        /**
         输出结果:
         Subscription 1:, Event: 0
         Subscription 1:, Event: 1
         Subscription 2:, Event: 1
         Subscription 1:, Event: 2
         Subscription 2:, Event: 2
         Subscription 1:, Event: 3
         Subscription 2:, Event: 3
         Subscription 3:, Event: 3
         Subscription 1:, Event: 4
         Subscription 2:, Event: 4
         Subscription 3:, Event: 4
         Subscription 1:, Event: 5
         Subscription 2:, Event: 5
         Subscription 3:, Event: 5
         Subscription 1:, Event: 6
         Subscription 2:, Event: 6
         Subscription 3:, Event: 6
         Subscription 1:, Event: 7
         Subscription 2:, Event: 7
         Subscription 3:, Event: 7
         Subscription 1:, Event: 8
         Subscription 2:, Event: 8
         Subscription 3:, Event: 8
         Subscription 1:, Event: 9
         Subscription 2:, Event: 9
         Subscription 3:, Event: 9
         Subscription 1:, Event: 10
         Subscription 2:, Event: 10
         Subscription 3:, Event: 10
         Subscription 1:, Event: 11
         Subscription 2:, Event: 11
         Subscription 3:, Event: 11
         Subscription 1:, Event: 12
         Subscription 2:, Event: 12
         Subscription 3:, Event: 12
         Subscription 1:, Event: 13
         Subscription 2:, Event: 13
         Subscription 3:, Event: 13

         */
        
        //MARK: - replay
        /**
         介绍:
         将源可观察序列转换为可连接序列,并向每个新订阅者重播缓冲区大小先前排放的数量。
         */
        
//        let intSequence = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
//            .replay(5)  // 缓存5个数据, 这个案例中会延迟5秒才有打印数据
//
//        _ = intSequence.subscribe(onNext: { print("Subscription 1:, Event: \($0)") })
//
//        delay(2) { _ = intSequence.connect() }
//
//
//        delay(4){
//            _ = intSequence.subscribe(onNext: { print("Subscription 2:, Event: \($0)") })
//        }
//
//        delay(8){
//            _ = intSequence.subscribe(onNext: { print("Subscription 3:, Event: \($0)") })
//        }
        
        
        /**
         输出结果:
         Subscription 1:, Event: 0
         Subscription 2:, Event: 0
         Subscription 1:, Event: 1
         Subscription 2:, Event: 1
         Subscription 1:, Event: 2
         Subscription 2:, Event: 2
         Subscription 1:, Event: 3
         Subscription 2:, Event: 3
         Subscription 1:, Event: 4
         Subscription 2:, Event: 4
         Subscription 3:, Event: 0
         Subscription 3:, Event: 1
         Subscription 3:, Event: 2
         Subscription 3:, Event: 3
         Subscription 3:, Event: 4
         Subscription 1:, Event: 5
         Subscription 2:, Event: 5
         Subscription 3:, Event: 5
         Subscription 1:, Event: 6
         Subscription 2:, Event: 6
         Subscription 3:, Event: 6
         Subscription 1:, Event: 7
         Subscription 2:, Event: 7
         Subscription 3:, Event: 7
         Subscription 1:, Event: 8
         Subscription 2:, Event: 8
         Subscription 3:, Event: 8
         Subscription 1:, Event: 9
         Subscription 2:, Event: 9
         Subscription 3:, Event: 9
         Subscription 1:, Event: 10
         Subscription 2:, Event: 10
         Subscription 3:, Event: 10
         Subscription 1:, Event: 11
         Subscription 2:, Event: 11
         Subscription 3:, Event: 11
         Subscription 1:, Event: 12
         Subscription 2:, Event: 12
         Subscription 3:, Event: 12
         Subscription 1:, Event: 13
         Subscription 2:, Event: 13
         Subscription 3:, Event: 13
         Subscription 1:, Event: 14
         Subscription 2:, Event: 14
         Subscription 3:, Event: 14
         Subscription 1:, Event: 15
         Subscription 2:, Event: 15
         Subscription 3:, Event: 15
         Subscription 1:, Event: 16
         Subscription 2:, Event: 16
         Subscription 3:, Event: 16
         Subscription 1:, Event: 17
         Subscription 2:, Event: 17
         Subscription 3:, Event: 17
         Subscription 1:, Event: 18
         Subscription 2:, Event: 18
         Subscription 3:, Event: 18
         Subscription 1:, Event: 19
         Subscription 2:, Event: 19
         Subscription 3:, Event: 19


         */
        
        
        //MARK: - multicast
        /**
         介绍:
         将源可观察序列转换为可连接序列,并通过指定的主题广播其发射。

         */
        
//        let subject = PublishSubject<Int>()
//
//        _ = subject.subscribe(onNext: { print("Subject: \($0)") })
//
//        let intSequence = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance).multicast(subject)
//
//        _ = intSequence.subscribe(onNext: { print("\tSubscriotion 1:, Event: \($0)") })
//
//        delay(2){
//            _ = intSequence.connect()
//        }
//
//        delay(4){
//            _ = intSequence.subscribe(onNext: { print("\tSubscription 2: Event: \($0)") })
//        }
//
//        delay(6){
//            _ = intSequence.subscribe(onNext: { print("\tSubscription 3:, Event: \($0)") })
//        }
        
        /**
         输出结果:
         Subject: 0
             Subscriotion 1:, Event: 0
         Subject: 1
             Subscriotion 1:, Event: 1
             Subscription 2: Event: 1
         Subject: 2
             Subscriotion 1:, Event: 2
             Subscription 2: Event: 2
         Subject: 3
             Subscriotion 1:, Event: 3
             Subscription 2: Event: 3
             Subscription 3:, Event: 3
         Subject: 4
             Subscriotion 1:, Event: 4
             Subscription 2: Event: 4
             Subscription 3:, Event: 4
         Subject: 5
             Subscriotion 1:, Event: 5
             Subscription 2: Event: 5
             Subscription 3:, Event: 5
         Subject: 6
             Subscriotion 1:, Event: 6
             Subscription 2: Event: 6
             Subscription 3:, Event: 6
         Subject: 7
             Subscriotion 1:, Event: 7
             Subscription 2: Event: 7
             Subscription 3:, Event: 7
         Subject: 8
             Subscriotion 1:, Event: 8
             Subscription 2: Event: 8
             Subscription 3:, Event: 8
         Subject: 9
             Subscriotion 1:, Event: 9
             Subscription 2: Event: 9
             Subscription 3:, Event: 9
         Subject: 10
             Subscriotion 1:, Event: 10
             Subscription 2: Event: 10
             Subscription 3:, Event: 10
         Subject: 11
             Subscriotion 1:, Event: 11
             Subscription 2: Event: 11
             Subscription 3:, Event: 11
         Subject: 12
             Subscriotion 1:, Event: 12
             Subscription 2: Event: 12
             Subscription 3:, Event: 12
         Subject: 13
             Subscriotion 1:, Event: 13
             Subscription 2: Event: 13
             Subscription 3:, Event: 13
         Subject: 14
             Subscriotion 1:, Event: 14
             Subscription 2: Event: 14
             Subscription 3:, Event: 14
         Subject: 15
             Subscriotion 1:, Event: 15
             Subscription 2: Event: 15
             Subscription 3:, Event: 15
         Subject: 16
             Subscriotion 1:, Event: 16
             Subscription 2: Event: 16
             Subscription 3:, Event: 16
         */
        
        
        //MARK: - catchErrorJustReturn
        /**
         介绍:
         通过返回一个发出单个元素然后终止的可观察序列,从错误事件中恢复。

         */
//        let disposeBag = DisposeBag()
//
//
//        let sequenceThatFails = PublishSubject<String>()
//
//        sequenceThatFails
//            .catchAndReturn("😊")
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        sequenceThatFails.onNext("😬")
//        sequenceThatFails.onNext("😨")
//        sequenceThatFails.onNext("😡")
//        sequenceThatFails.onNext("🔴")
//        sequenceThatFails.onError(TestError.test)
        
        
        /**
         输出结果:
         😬
         😨
         😡
         🔴
         😊      这是捕捉到了错误信息打印出来的
         */
        
        //MARK: - catchError
        /**
         介绍:
         通过切换到提供的恢复可观察序列从错误事件中恢复。

         */
//        let disposeBag = DisposeBag()
//
//        let sequenceThatFails = PublishSubject<String>()
//        let recoverySequence = PublishSubject<String>()
//
//        sequenceThatFails
//            .catch{
//                print("Error: ", $0)
//                return recoverySequence
//            }
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
//
//        sequenceThatFails.onNext("😬")
//        sequenceThatFails.onNext("😨")
//        sequenceThatFails.onNext("😡")
//        sequenceThatFails.onNext("🔴")
//        sequenceThatFails.onError(TestError.test)
//
//        recoverySequence.onNext("😊")
        /**
         输出结果:
         😬
         😨
         😡
         🔴
         Error:  test
         😊
         */
        
        
        //MARK: - retry
        /**
         介绍:
         通过重新订阅可观察序列,无限地恢复反复的错误事件。

         */
//        let disposeBag = DisposeBag()
//        var count = 1
//
//        let sequenceThatErrors = Observable<String>.create { observer in
//            observer.onNext("count: \(count)   ----  🍎")
//            observer.onNext("count: \(count)   ----  🍐")
//            observer.onNext("count: \(count)   ----  🍊")
//
//            if count == 1 {
//                observer.onError(TestError.test)
//                print("Error encountered")
//                count += 1
//            }
//
//            observer.onNext("count: \(count)   ----  🐶")
//            observer.onNext("count: \(count)   ----  🐱")
//            observer.onNext("count: \(count)   ----  🐭")
//            observer.onCompleted()
//
//            return Disposables.create()
//        }
//
//        sequenceThatErrors.retry()
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        
        
        /**
         输出结果:
         count: 1   ----  🍎
         count: 1   ----  🍐
         count: 1   ----  🍊
         Error encountered    发生错误后发送error信号,retry会重头执行代码
         count: 2   ----  🍎
         count: 2   ----  🍐
         count: 2   ----  🍊
         count: 2   ----  🐶
         count: 2   ----  🐱
         count: 2   ----  🐭
         */
        
        //MARK: - retry(_:)
        /**
         介绍:
         通过重新订阅可观察序列,重复从错误事件中恢复,最大重试次数为maxAttemptCount。
         */
//        let disposeBag = DisposeBag()
//        var count = 1
//
//        let sequenceThatErrors = Observable<String>.create { observer in
//
//            observer.onNext("count: \(count)   ----  🍎")
//            observer.onNext("count: \(count)   ----  🍐")
//            observer.onNext("count: \(count)   ----  🍊")
//
//            if count < 5 {
//                observer.onError(TestError.test)
//                print("Error encountered, count: \(count)")
//                count += 1
//            }
//
//            observer.onNext("count: \(count)   ----  🐶")
//            observer.onNext("count: \(count)   ----  🐱")
//            observer.onNext("count: \(count)   ----  🐭")
//            observer.onCompleted()
//
//            return Disposables.create()
//        }
//
//        sequenceThatErrors.retry(4)
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        
         /*输出结果:
          count: 1   ----  🍎
          count: 1   ----  🍐
          count: 1   ----  🍊
          Error encountered, count: 1
          count: 2   ----  🍎
          count: 2   ----  🍐
          count: 2   ----  🍊
          Error encountered, count: 2
          count: 3   ----  🍎
          count: 3   ----  🍐
          count: 3   ----  🍊
          Error encountered, count: 3
          Unhandled error happened: test
         */
        
        
        //MARK: - debug
        /**
         介绍:
         打印出所有订阅、事件和处置。
         */
//        let disposeBag = DisposeBag()
//        var count = 1
//
//        let sequenceThatErrors = Observable<String>.create { observer in
//            observer.onNext("count: \(count) ----  🍎")
//            observer.onNext("count: \(count) ----  🍐")
//            observer.onNext("count: \(count) ----  🍊")
//
//            if count < 5 {
//                observer.onError(TestError.test)
//                print("Error encountered")
//                count += 1
//            }
//
//            observer.onNext("count: \(count) ----  🐶")
//            observer.onNext("count: \(count) ----  🐱")
//            observer.onNext("count: \(count) ----  🐭")
//            observer.onCompleted()
//
//            return Disposables.create()
//        }
//
//        sequenceThatErrors
//            .retry(3)
//            .debug()
//            .subscribe(onNext: { print($0) })
//            .disposed(by: disposeBag)
        
        /**
         输出结果:
         2023-02-08 10:45:04.329: ViewController.swift:1292 (test()) -> subscribed
         2023-02-08 10:45:04.354: ViewController.swift:1292 (test()) -> Event next(count: 1 ----  🍎)
         count: 1 ----  🍎
         2023-02-08 10:45:04.355: ViewController.swift:1292 (test()) -> Event next(count: 1 ----  🍐)
         count: 1 ----  🍐
         2023-02-08 10:45:04.355: ViewController.swift:1292 (test()) -> Event next(count: 1 ----  🍊)
         count: 1 ----  🍊
         Error encountered
         2023-02-08 10:45:04.357: ViewController.swift:1292 (test()) -> Event next(count: 2 ----  🍎)
         count: 2 ----  🍎
         2023-02-08 10:45:04.357: ViewController.swift:1292 (test()) -> Event next(count: 2 ----  🍐)
         count: 2 ----  🍐
         2023-02-08 10:45:04.357: ViewController.swift:1292 (test()) -> Event next(count: 2 ----  🍊)
         count: 2 ----  🍊
         Error encountered
         2023-02-08 10:45:04.357: ViewController.swift:1292 (test()) -> Event next(count: 3 ----  🍎)
         count: 3 ----  🍎
         2023-02-08 10:45:04.357: ViewController.swift:1292 (test()) -> Event next(count: 3 ----  🍐)
         count: 3 ----  🍐
         2023-02-08 10:45:04.358: ViewController.swift:1292 (test()) -> Event next(count: 3 ----  🍊)
         count: 3 ----  🍊
         Error encountered
         2023-02-08 10:45:04.360: ViewController.swift:1292 (test()) -> Event error(test)
         Unhandled error happened: test
         2023-02-08 10:45:04.361: ViewController.swift:1292 (test()) -> isDisposed

         */
        
        //MARK: - try Yourself
//        let disposeBag = DisposeBag()
//
//        _ = Observable.just("Hello, RxSwift!")
//          .debug("Observable")
//          .subscribe(onNext: { print($0) })
//          .disposed(by: disposeBag)
        /**
         输出结果:
         2023-02-08 10:50:57.082: Observable -> subscribed
         2023-02-08 10:50:57.108: Observable -> Event next(Hello, RxSwift!)
         Hello, RxSwift!
         2023-02-08 10:50:57.111: Observable -> Event completed
         2023-02-08 10:50:57.111: Observable -> isDisposed
         */
    }
}


extension ObservableType {
    func addObserver(_ id: String) -> Disposable {
        subscribe{ print("Subscription: ", id, "Event: ", $0) }
    }
}

public func delay(_ delay: Double, closure: @escaping () -> Void){
    DispatchQueue.main.asyncAfter(deadline: .now() + delay){
        closure()
    }
}



上一篇下一篇

猜你喜欢

热点阅读