This repository has no description
composable-atmosphere-constellation
/
Sources
/
ComposableAtmosphereConstellation
/
TaskUnifier.swift
671 B
28 lines
1public actor TaskUnifier<Key: Hashable & Sendable, Value: Sendable> {
2 private var tasks: [Key: Task<Value, Error>] = [:]
3
4 public init() {}
5
6 public func value(
7 for key: Key,
8 operation: @Sendable @escaping () async throws -> Value
9 ) async throws -> Value {
10 if let task = tasks[key] {
11 return try await task.value
12 }
13
14 let task = Task {
15 try await operation()
16 }
17 tasks[key] = task
18
19 do {
20 let value = try await task.value
21 tasks[key] = nil
22 return value
23 } catch {
24 tasks[key] = nil
25 throw error
26 }
27 }
28}