-
Notifications
You must be signed in to change notification settings - Fork 224
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(crash): introduced throttling for UI updates to avoid UI freeze (#8)
* fix(freeze): introduce throttler to updating UI to avoid crashes
- Loading branch information
Showing
5 changed files
with
77 additions
and
66 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// | ||
// Throttler.swift | ||
// Enchanted | ||
// | ||
// Created by Augustinas Malinauskas on 29/12/2023. | ||
// | ||
|
||
import Foundation | ||
|
||
class Throttler { | ||
private var workItem: DispatchWorkItem? | ||
private var lastRun: Date = .distantPast | ||
private let queue: DispatchQueue | ||
private let delay: TimeInterval | ||
|
||
init(delay: TimeInterval, queue: DispatchQueue = DispatchQueue.main) { | ||
self.delay = delay | ||
self.queue = queue | ||
} | ||
|
||
func throttle(_ block: @escaping () -> Void) { | ||
workItem?.cancel() | ||
|
||
let item = DispatchWorkItem { [weak self] in | ||
self?.lastRun = Date() | ||
block() | ||
} | ||
self.workItem = item | ||
|
||
let delayFactor = Date().timeIntervalSince(lastRun) >= delay ? 0 : delay | ||
queue.asyncAfter(deadline: .now() + delayFactor, execute: item) | ||
} | ||
} |
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
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