RxSwift share() 函数的理解

倒计时例子:

func shareDemo(){
        let timer = Observable.interval(.seconds(1), scheduler: MainScheduler.instance)
            .share(replay: 3, scope: .forever)
        
        let _ = timer
            .subscribe(onNext: {
                print("----1:\($0)")
            }, onError: nil, onCompleted: nil, onDisposed: nil)
        
        after(3) {
            let _ = timer
                .subscribe(onNext: {
                    print("----2:\($0)")
                }, onError: nil, onCompleted: nil, onDisposed: nil)
        }
        
        after(5) {
            let _ = timer
                .subscribe(onNext: {
                    print("----3:\($0)")
                }, onError: nil, onCompleted: nil, onDisposed: nil)
        }
    }
    
    ///延时操作
func after(_ delay: Double, block: @escaping ()->()){
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: block)
    }
/* 打印结果:
         ----1:0
         ----1:1
         ----1:2
         ----2:0
         ----2:1
         ----2:2
         ----1:3
         ----2:3
         ----1:4
         ----2:4
         ----3:2
         ----3:3
         ----3:4
         ----1:5
         ----2:5
         ----3:5
         ----1:6
         ----2:6
         ----3:6

可以发现,从第3秒开始打印第二个订阅,第二个订阅是从0开始打印的,从第5秒开始打印第三个订阅,是从2开始打印。 源信号的 .share(replay: 3, scope: .forever),信号会保存 3 个数据,当我们下次订阅的时候,这三个数据直接拿来用。

例子2:

func configShare(with shares: Int){
        let pubObject = PublishSubject()

        var a: Observable
        if shares > 0 {
             a = pubObject
                .map { (i) -> Int in
                    print("Map == \(i)")
                    return i * 2
                }.share(replay: shares, scope: .forever)
        }else{
            a = pubObject
                .map { (i) -> Int in
                    print("Map == \(i)")
                    return i * 2
                }
        }

        a.subscribe (onNext:{ (m) in
                print("1 == \(m)")
            }).disposed(by: dispose)

        pubObject.onNext(1)
        pubObject.onNext(2)
        
        let _ = a.subscribe(onNext: { (m) in
            print("2 == \(m)")
        }, onError: nil, onCompleted: nil, onDisposed: nil)
        
        pubObject.onNext(3)
        pubObject.onCompleted()
    }

调用self.configShare(with: )的时候,打印数据如下

share == 0 的时候打印结果
Map == 1
1 == 2
Map == 2
1 == 4
Map == 3
1 == 6
Map == 3
2 == 6

share == 1 的时候打印结果
Map == 1
1 == 2
Map == 2
1 == 4
2 == 4
Map == 3
1 == 6
2 == 6

share == 2 的时候打印结果
Map == 1
1 == 2
Map == 2
1 == 4
2 == 2
2 == 4
Map == 3
1 == 6
2 == 6

个人理解:当没有 share的时候,源信号没有保存数据,所以在 pubObject.onNext()只会的订阅都不会触发了,如果pubObject.onNext()之前有多个订阅,那么发布信号的时候,都会调用map函数;当share == 1的时候,源信号会保存一个数据,所以pubObject.onNext(2)的时候,会保存 一个数据在源信号里面此时的数据是4,所以会打印 2 == 4。同理,当share == 2的时候,会保存两个数据在源信号里面,一个是 pubObject.onNext(1) 一个是 pubObject.onNext(2),所以会打印 2 == 2

你可能感兴趣的:(RxSwift share() 函数的理解)