Last active
September 13, 2024 09:09
-
-
Save banjun/f7de93e13cdb55797a7845f61a25e15e to your computer and use it in GitHub Desktop.
Timer.scheduledTimer on MainActor
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 | |
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