JP Sugarbroad
11/12/2024, 10:12 PMJP Sugarbroad
11/12/2024, 10:17 PMlaunch {
try {
awaitCancellation()
} finally {
socket.close()
}
}
JP Sugarbroad
11/12/2024, 11:01 PMJob(coroutineContext.job).invokeOnCompletion
is a better option.JP Sugarbroad
11/12/2024, 11:02 PMJob.invokeOnCancelling
isn't a thing.JP Sugarbroad
11/13/2024, 2:35 AMlaunch(start = CoroutineStart.ATOMIC) {
try {
awaitCancellation()
} finally {
socket.close()
}
}
JP Sugarbroad
11/13/2024, 2:35 AMDmitry Khalanskiy [JB]
11/14/2024, 11:35 AMIt's unfortunate thatFor these purposes,isn't a thing.Job.invokeOnCancelling
Job.invokeOnCompletion
also shouldn't be a thing. https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#close-- socket.close()
can throw exceptions, and `invokeOnCompletion`'s contract does not allow that. invokeOnCompletion
is a low-level function mostly useful for writing concurrent data structures.
In isolation, your solution seems perfectly fine to me. It's slightly suspicious that it looks like several coroutines are going to interact with one socket (another option to consider could be to launch a single coroutine and interact with it via a channel, for example), but I can imagine cases where what you're doing is the best approach.JP Sugarbroad
11/14/2024, 11:32 PM