Throttling in Swift without going reactive

馋奶兔 提交于 2020-07-05 13:51:30

问题


Is there a simple way of implementing the Throttle feature in Reactive programming without having to use RxSwift or similar frameworks.

I have a textField delegate method that I would like not to fire every time a character is inserted/deleted.

How to do that using vanilla Foundation?


回答1:


Yes it is possible to achieve.

But first lets answer small question what is Throttling?

In software, a throttling process, or a throttling controller as it is sometimes called, is a process responsible for regulating the rate at which application processing is conducted, either statically or dynamically.

Example of the Throttling function in the Swift.

In case that you have describe with delegate method you will have issue that delegate method will be called each time. So I will write short example how it impossible to do in the case you describe.

class ViewController: UIViewController {

    var timer: Timer?

    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }

    func validate() {
        print("Validate is called")
    }
}

extension ViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        timer?.invalidate()

        timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.validate), userInfo: nil, repeats: false);

        return true
    }

}


来源:https://stackoverflow.com/questions/43322682/throttling-in-swift-without-going-reactive

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