【问题标题】:Is there a way to not trigger the init value of the Variable<T>?有没有办法不触发变量<T> 的初始值?
【发布时间】:2017-04-19 15:42:32
【问题描述】:

见下面的代码。

class ViewController4: UIViewController {
    var disposeBag = DisposeBag()
    let v = Variable(0)

    override func viewDidLoad() {
        super.viewDidLoad()

        v.asObservable()
            .subscribe(onNext: { print($0) })
            .disposed(by: disposeBag)

        v.value = 1
    }
}

运行时会打印

0
1

但是,我不希望它在0 上运行,或者说0 只是用于启动v 的值。我可以这样做吗?还是必须在我使用的时间点推迟代码?

【问题讨论】:

    标签: rx-swift


    【解决方案1】:

    您可以使用运算符.skip 来抑制发出的 N 个第一个元素。因此,在您的情况下,skip(1) 将抑制初始化值。

    http://reactivex.io/documentation/operators/skip

    v.asObservable().skip(1)
            .subscribe(onNext: { print($0) })
            .disposed(by: disposeBag)
    
    v.value = 1
    //Output : 1
    
    v.value = 2
    v.value = 3
    //Output : 1 2 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多