延迟 2.3.6

Delayed 2.3.6

Eonfluxor 维护。



Delayed 2.3.6

  • 作者:
  • Eonflux - Hassan Uriostegui

alternate text

CocoaPods compatible GitHub release Swift 4.0 platforms Build Status

什么是 Kron?

Kron 是一个可重置的计时器管理器,通过统一的 API 提供了 4 种模式。Kron 负责可重置计时器的相关实现,同时确保适当的内存管理而无需额外工作。

  1. Kron.debounce:立即调用并拒绝调用,直到超时结束
  2. Kron.debounceLast:与 debounce 相同,但超时后还会执行最后一次调用
  3. Kron.idle:在超时期间未被调用的情况下执行最后一次调用
  4. Kron.watchdog:与 idle 相同,但可以通过 watchDogCancel 取消

CocoaPods

如果您使用 CocoaPods 管理依赖,只需将 Kron 添加到您的 Podfile

pod 'Delayed', '> 2.2.2'

然后导入模块:

import Delayed

为什么选择 Kron?

创建一个可重置的计时器需要一个类似的设置:

class SomeClass{
    var timer:Timer?
    
    /// create timer
    func createTimer(){
        assert( timer == nil, "Please call cancelTimer first" )
        
        timer = Timer(timeInterval: TimeInterval(1.0), target: self, selector: #selector(timerTick), userInfo: nil, repeats: false)
        RunLoop.main.add(timer!, forMode: .commonModes)
    }
    
    // cancel timer
    func cancelTimer(){
        if let aTimer = timer {
            aTimer.invalidate()
        }
        
        timer = nil
    }
    
    // restart timer
    func restartTimer(){
        cancelTimer()
        createTimer()
    }
    
    /// handle callback
    @objc func timerTick(_ timer:Timer){
        timer.invalidate()
        //Do something
    }
}

怎样才能一行完成呢?

Kron 通过内部管理一个可以通《resetKey 访问的计时器映射表来处理所有这些设置。递归调用相同的 resetKey 会导致特定计时器在所有模式下重置。

Kron.idle(timeOut:1.0, resetKey:"updateUI"){ (key,context) in
     
}

所以主要区别在于:

  • Timer 实例返回问题,Kron 通过 [KronKey : Timer] 字典内部管理计时器。这使得从远端组件或线程调用以键值访问计时器的 Kron 变得简单,并且只需一行代码。

  • KronKey 可以是 String 结构或 AnyObject 实例。如果传递了一个对象,键将从对象的指针推断出来。使用相同键的方法调用会导致所有计时器模式重置。

  • 可以提供可选的 context,类型为 Any?。它在内部用弱引用 包装,以防止保留循环。然后,上下文可以选择传递给 timeOut 闭包。

实际应用

防抖滚动

此示例将确保在用户滚动时每秒更新 UI。此外,使用 debounceLast 确保在 timeOut 中应用最后一次调用。这将保证执行最后一个事件。(您还可以使用 debounce 进行传统防抖。)

func didScroll(){
	Kron.debounceLast(timeOut: 1, resetKey: "scroll") { (keu, context) in
   		//updateUI     
	}
}

空闲和确保上下文

此示例将仅在用户 5 秒内未输入时保存文档。在 timeOut 闭包中,我们检查 KronKey 是否等于当前文档,否则终止保存操作。

var currentDocument:NSObject;

func textViewDidChange(){
	autoSave()
}

func autoSave(){
    Kron.idle(timeOut:10.0, resetKey:self.currentDocument){ [weak self] (key,context) in
          
        let aDocument = key as? NSObject
        guard aDocument == self?.currentDocument else{
            return
        }
        self?.saveNow()
    }
}

func saveNow(){
  //save only if current document is still active
}

看门狗

以下示例展示了如何对不同 API 请求添加看门狗。

func startApiRequest(_ endPointURL:String){
    
    let watchdogkey = "ApiRequest\(endPointURL)"
    
    Kron.watchDog(timeOut:10.0, resetKey:watchdogkey){ (key,context) in
        // retry or something else?
        assert(false, "print api is not responding!")
    }
    
    SomeClass.loadApi(endPointURL){
        
        Kron.watchDogCancel(watchdogkey)
        
    }
}

文档

使用 jazzy 自动生成的文档,托管在 github 上,可在此处查看

文档

代码片段

请审查测试单元,以了解全面实施示例。

在所有情况下,通过使用相同的键调用Kron,将重置计时器。(有关静态键空间的更多信息,请参阅下文静态与实例)。

  • 空闲计时器
Kron.idle(timeOut:1.0, resetKey:"keyStrokes"){ (key,context) in
      print("performed after 1 second of inactivity")
}
  • 去抖动器
Kron.debounce(timeOut:1.0, resetKey:"Scroll"){ (key,context) in
      print("performed immediately and again no sooner than 1 second")
}
  • 去抖动器并执行最后
Kron.debounceLast(timeOut:1.0, resetKey:"Scroll"){ (key,context) in
      print("performed immediately and again no sooner than 1 second")
      print("also performs the last call after 1 second of inactivity")
}
  • 看门狗
Kron.watchdog(timeOut:10.0, resetKey:"ApiResponse"){ (key,context) in
      print("performed  after 10 seconds unless canceled")

}

...

// Called somewhere else to abort the timeOut
Kron.watchdogCancel("ApiResponse")

静态与实例

您可以使用提供的静态函数。内部 Kron 管理了4个单例,以防止不同模式之间的键冲突。

//Debouncer
Kron.debounce

//Debouncing Last
Kron.debounceLast

//Idle
Kron.idle

//Watchdog
Kron.watchdog

可选地,您还可以实例化 Kron 以在该实例中管理自己的键空间。

let myKron = Kron()
myKron( ...

有问题吗?

如果您需要任何帮助,请访问我们的GitHub问题。如果您在存档中找不到任何解决方案,请随意创建一个问题。

您也可以在以下联系方式找到我们

contact@example.com

关于

Kron最初由Hassan Uriostegui作为Objective-C框架构建。现在作为under the Eonflux collective的Swift开源框架发布。查看我们的其他项目,并加入我们的创新之流