Cancellation with async tasks #1658
-
I have an action in my reducer that returns a case .someAction:
state.connectionState = .connecting
return .run { send in
let result1 = try await client.someOperation1()
let result2 = try await client.someOparation2(result1)
await send(.someActionResult(result2))
} Is there a way to apply a timeout to either the individual async calls inside the |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 10 replies
-
There is easy way to timeout async code in Swift, but you can do it manually, or make your own little operator to handle it: case .someAction:
state.connectionState = .connecting
return .run { send in
try await withThrowingTaskGroup(Void.self) { group in
group.addTask {
let result1 = try await client.someOperation1()
let result2 = try await client.someOparation2(result1)
await send(.someActionResult(result2))
}
group.addTask {
try await self.clock.sleep(for: .seconds(10))
throw TimeoutError()
}
try await group.next()
group.cancelAll()
}
} |
Beta Was this translation helpful? Give feedback.
-
Excellent, thanks @mbrandonw. It is an "easy" way but certainly a bit more complicated than ising |
Beta Was this translation helpful? Give feedback.
-
Sorry to revive this old thread but I'm having some issues with timeout. I swear I have seen this work several times before but lately it just fails. I see the TimeoutError get thrown (by setting a breakpoint on that line) but the error just disappears after that. It doesn't get handled by the I've tried putting my Am I handling this error situation incorrectly? Here's my return .run(operation: { [state] send in
try await withThrowingTaskGroup(
of: Void.self,
body: { group in
group.addTask {
try await client.initializeVideo(state.channelArn)
try await client.connect()
await send(.connectResult(.success(true)))
}
group.addTask {
try await Task.sleep(nanoseconds: 10 * NSEC_PER_SEC)
throw TimeoutError.initializationTimeout
}
try await group.next()
group.cancelAll()
})
}, catch: { error, send in
await send(.connectResult(.failure(error)))
}) |
Beta Was this translation helpful? Give feedback.
There is easy way to timeout async code in Swift, but you can do it manually, or make your own little operator to handle it: