Skip to content

Instantly share code, notes, and snippets.

@wotjd
Created June 25, 2024 18:10
Show Gist options
  • Save wotjd/e3695ce320aa94c970fed945e6125b58 to your computer and use it in GitHub Desktop.
Save wotjd/e3695ce320aa94c970fed945e6125b58 to your computer and use it in GitHub Desktop.
results using previous task without creating new task
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