Created
June 25, 2024 18:10
-
-
Save wotjd/e3695ce320aa94c970fed945e6125b58 to your computer and use it in GitHub Desktop.
results using previous task without creating new task
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
actor MyActor { | |
var currentTask: Task<Void, Error>? | |
@discardableResult | |
func run<Value>( | |
_ action: @Sendable (_ actor: isolated MyActor) async throws -> Value | |
) async rethrows -> Value { | |
try await action(self) | |
} | |
} | |
let myActor = MyActor() | |
try await myActor.run { myActor in | |
if let currentTask = myActor.currentTask { | |
return try await currentTask.value | |
} | |
let newTask = Task { /* some heavy task */ } | |
myActor.currentTask = newTask | |
defer { myActor.newTask = nil } | |
return try await newTask.value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment