Created
December 16, 2022 22:31
-
-
Save boraseoksoon/55eae9067da7ce9a23c1984987a0ac3d to your computer and use it in GitHub Desktop.
task delay swift
This file contains hidden or 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 | |
| // reference: https://www.swiftbysundell.com/articles/delaying-an-async-swift-task/ | |
| let loadingSpinnerTask = Task.delayed(byTimeInterval: 0.15) { | |
| self.showLoadingSpinner() | |
| } | |
| Task { | |
| await a() | |
| loadingSpinnerTask.cancel() | |
| b() | |
| } | |
| extension Task where Failure == Error { | |
| static func delayed( | |
| byTimeInterval delayInterval: TimeInterval, | |
| priority: TaskPriority? = nil, | |
| operation: @escaping @Sendable () async throws -> Success | |
| ) -> Task { | |
| Task(priority: priority) { | |
| let delay = UInt64(delayInterval * 1_000_000_000) | |
| try await Task<Never, Never>.sleep(nanoseconds: delay) | |
| return try await operation() | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment