【问题标题】:RxSwift - block/stop/ignore event if condition metRxSwift - 如果满足条件,则阻止/停止/忽略事件
【发布时间】:2021-11-29 15:28:04
【问题描述】:

过滤一个 Observable 列表后,我可能有一个空列表。我只对包含填充列表的事件感兴趣。有什么办法可以阻止空事件传播到onNext?


        let source: BehaviorRelay<[Int]> = .init(value: [])

        source
            .map { nums -> [Int] in
                return nums.filter { $0 < 10 }
            }
            /// What can go here to stop/block/ignore an empty list
            .subscribe(onNext: { nums in
               print("OKPDX \(nums)")
            })

        source.accept([1, 9, 13])
        // prints "[1, 9]" (all good)

        source.accept([20, 22, 101])
        // prints "[]" (not desirable, I'd rather not know)

【问题讨论】:

    标签: ios swift rx-swift


    【解决方案1】:

    使用.filter 怎么样?你可以这样做:

    .map { nums -> [Int] in
            return nums.filter { $0 < 10 }
         }
    .filter { !$0.isEmpty }
    

    或者您也可以在收到这样的事件时验证:

    .subscribe(onNext: { nums in
          guard !nums.isEmpty else { return }
          print("OKPDX \(nums)")
    })
    

    【讨论】:

    • 正是我所追求的,谢谢
    猜你喜欢
    • 2023-04-05
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多