RxSwift: Observable while a button holds down

流过昼夜 提交于 2019-12-21 06:04:22

问题


How to create Observable which streams an event repeatedly while a button holds down?


回答1:


Even I was looking for a solution for your question. I got help from RxSwift slack channel.

    let button = submitButton.rx_controlEvent([.TouchDown])
      button
        .flatMapLatest { _ in
            Observable<Int64>.interval(0.1, scheduler: MainScheduler.instance)
                .takeUntil(self.submitButton.rx_controlEvent([.TouchUpInside]))
        }
        .subscribeNext{ x in print("BOOM \(x)") }
        .addDisposableTo(disposeBag)

//prints BOOM 0 BOOM 1 BOOM 2 BOOM 3 BOOM 4 BOOM 5 for every 0.1 seconds

And also Check Interval Documentation.Thanks to @jari of RxSwift slack channel.




回答2:


To continue on rootcoder response, I had a situation where I had to recognize one longpress greater than three seconds

 let signinLongpress = signinButton.rx.controlEvent([.touchDown])
    signinLongpress
        .flatMapLatest { _ in
            Observable<Int64>.interval(3, scheduler: MainScheduler.instance)
                .take(1)
        }
        .subscribe(onNext:{ _ in print("do fun stuff only once when longpress detected")})
        .disposed(by: disposeBag)


来源:https://stackoverflow.com/questions/39120624/rxswift-observable-while-a-button-holds-down

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!