2
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

updated at

RxSwiftでリアクティブにインターバル間隔を変えるintervalを作る方法 #rxSwift

元々質問のつもりで作ったんですが自己解決しました
タイトルの通り、intervalの間隔をリアクティブに対応する関数を作りました。

interval.gif

インターバル値を都度変更する関数
public func interval(throttle throttle:Variable<Double>) -> Observable<Double> {

    return create { (observer) -> Disposable in

        var intervalDisposer:Disposable?
        return throttle.subscribeNext { (chagedValue) -> Void in
            intervalDisposer?.dispose()
            intervalDisposer = interval(chagedValue, MainScheduler.sharedInstance).subscribeNext({ count -> Void in
                observer.on(.Next(chagedValue))
            })
        }
    }
}

いかが実際に利用している箇所のコードとなります。



import UIKit
import RxSwift
import RxCocoa

class ViewController: UIViewController {

    @IBOutlet weak var incrementalLabel: UILabel!
    @IBOutlet weak var addDurationButton: UIButton!
    @IBOutlet weak var decDurationButton: UIButton!
    @IBOutlet weak var durationTimeLabel: UILabel!

    var durationTime = Variable(0.3)
    var incrementValue = Variable(0)

    var disposeBag:DisposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        //該当呼び出し箇所 <------
        interval(throttle: durationTime).subscribeNext { _ in
            self.incrementValue.value += 1
        }.addDisposableTo(disposeBag)


        //txt
        incrementValue.map{ return "\($0)"}.bindTo(incrementalLabel.rx_text).addDisposableTo(disposeBag)

        //chnage durationtime
        addDurationButton.rx_tap.subscribeNext {
            self.durationTime.value += 0.1
            self.durationTime.value = abs(self.durationTime.value)
        }.addDisposableTo(disposeBag)

        decDurationButton.rx_tap.subscribeNext {
            self.durationTime.value -= 0.1
            self.durationTime.value = abs(self.durationTime.value)
        }.addDisposableTo(disposeBag)

        self.durationTime.map{ return "\($0)" }.bindTo(durationTimeLabel.rx_text).addDisposableTo(disposeBag)


    }

}

以下に既存コードを置いています。
https://github.com/m0a-mystudy/adjustableInterval

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
2
Help us understand the problem. What are the problem?