Skip to content

Instantly share code, notes, and snippets.

@VladimirBrejcha
Last active August 1, 2020 19:23
Show Gist options
  • Save VladimirBrejcha/a3ecc00253e02a1aeb5956015dfd9ec9 to your computer and use it in GitHub Desktop.
Save VladimirBrejcha/a3ecc00253e02a1aeb5956015dfd9ec9 to your computer and use it in GitHub Desktop.
AutoRefreshable.swift
import Foundation
protocol Refreshable {
associatedtype DataType
func refresh(with data: DataType)
}
protocol AutoRefreshable: AnyObject, Refreshable {
var timer: Timer? { get set }
var dataSource: (() -> DataType)? { get set }
var refreshInterval: Double { get set }
}
extension AutoRefreshable {
func beginRefreshing() {
guard let dataSource = dataSource else {
print("AutoRefreshable.beginRefreshing failed, dataSource was nil")
return
}
if timer != nil {
timer?.invalidate()
timer = nil
}
refresh(with: dataSource())
timer = Timer.scheduledTimer(
withTimeInterval: refreshInterval,
repeats: true
) { [weak self] timer in
guard let self = self else {
timer.invalidate()
return
}
self.refresh(with: dataSource())
}
}
func stopRefreshing() {
timer?.invalidate()
timer = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment