Last active
August 1, 2020 19:23
-
-
Save VladimirBrejcha/a3ecc00253e02a1aeb5956015dfd9ec9 to your computer and use it in GitHub Desktop.
AutoRefreshable.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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