美文网首页
RXSwift - transform operators (t

RXSwift - transform operators (t

作者: 内蒙小猿 | 来源:发表于2020-08-21 08:35 被阅读0次

    toArray : 是把 observable 结束时所有的事件值变成一个数组,只要这个 observable 不结束,这个转变就不会发生。

            let bag = DisposeBag()
            
            let number = PublishSubject<Int>()
            
            number.asObserver().toArray().subscribe { (arr) in
                print("toArray  \(arr)")
            }.disposed(by: bag)
            
            number.onNext(1)
            number.onNext(2)
            number.onNext(3)
            number.onCompleted()
    
    

    \color{#DEB887}{执行结果:toArray success([1, 2])}

    scan :它可以对observable序列中的每一个事件进行 “累加”, 最终订阅到的 “累加” 的结果。

            let bag = DisposeBag()
            
            let number = PublishSubject<Int>()
            
            number.scan(0) { (old, new) -> Int in
                return old + new
            }.subscribe { (num) in
                print("scan  \(num)")
            }.disposed(by: bag)
            
            number.onNext(1)
            number.onNext(2)
            number.onNext(3)
            number.onCompleted()
    
    

    \color{#DEB887}{执行结果: \ 1 \ 3 \ 6 \qquad completed }

    note

    • \color{##A9A9A9}{ 1 = 0 + 1 }

    • \color{##A9A9A9}{ 3 = (0 + 1) + 2 }

    • \color{##A9A9A9}{ 6 = ((0 + 1) + 2) + 3 }

    map :自定义事件变化行为

            let bag = DisposeBag()
            
            let number = PublishSubject<Int>()
            
            number.map { (value) -> Int in
                return value * value
            }.subscribe { (num) in
                print("map  \(num)")
            }.disposed(by: bag)
            
            number.onNext(1)
            number.onNext(2)
            number.onNext(3)
            number.onCompleted()
    
    

    \color{#DEB887}{执行结果:\ 1 \ 4 \ 9 \qquad completed }

    note

    • \color{##A9A9A9}{ 1 = 1 * 1 }

    • \color{##A9A9A9}{ 4 = 2 * 2 }

    • \color{##A9A9A9}{ 9 = 3 * 3 }

    相关文章

      网友评论

          本文标题:RXSwift - transform operators (t

          本文链接:https://www.haomeiwen.com/subject/oqxejktx.html