Skip to content

Instantly share code, notes, and snippets.

@banjun
Last active September 13, 2024 09:09
Show Gist options
  • Save banjun/f7de93e13cdb55797a7845f61a25e15e to your computer and use it in GitHub Desktop.
Save banjun/f7de93e13cdb55797a7845f61a25e15e to your computer and use it in GitHub Desktop.
Timer.scheduledTimer on MainActor
import Foundation
extension Timer {
@MainActor @discardableResult static func scheduledTimerOnMainRunLoop(withTimeInterval: TimeInterval, repeats: Bool, block: @escaping @MainActor (Timer) -> Void) -> Timer {
// The doc says: Creates and returns a new NSTimer object initialized with the specified block object and schedules it on the current run loop
// But the block is not annotated with @MainActor and we need MainActor.assumeIsolated
// Since Timer is non-Sendable, capture by nonisolated(unsafe) to pass from nonisolated context to MainActor.
Timer.scheduledTimer(withTimeInterval: withTimeInterval, repeats: repeats) { timer in
nonisolated(unsafe) let timer: Timer = timer
MainActor.assumeIsolated {
block(timer)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment