CoroutineScope equivalent in swift concurrency

Kotlin has the concept of a CoroutineScope which allows you to launch Coroutines (equivalent to Swift Tasks) in them. The Coroutines inherit the CoroutineScope context implicitly. This is useful for when you have to launch multiple Coroutines in a single Android Activity (equivalent to UIKit UIViewController). In the Activity's onDestroy method, I can simply call coroutineScope.cancel() to cancel all Coroutines launched in it.

Watching the WWDC video on structured concurrency it seems the only thing mentioned equivalent to what I'd like to do in a UIViewController that's similar, is to store any Task created to a dictionary or list of tasks and call tasks.forEach { $0.cancel() }.

To conclude, is there no concept of a CoroutineScope in Swift concurrency that creates a top level instance, in a UIViewController say, where I can initiate child Tasks that implicitly inherit the context of the Scope that I can then call cancel on in the viewDidUnload method or another lifecycle method?

1 Like

No, there's nothing that will implicitly pick up all local async work.

It’s been a year but I’ve wanted to follow up now that I’m running into an issue.

@Jon_Shier Do you know of any proposals or future directions of Swift that will add this feature? I’m trying to dig through proposals and it doesn’t seem like I can find anything related to this feature of concurrency. However, I feel this is supported in other structured concurrency systems in Python and Kotlin

There's nothing like this being proposed yet, I suggest you can start a thread in the evolution category and sketch out the shape of what you're looking for and start discussing with the community in the expected shape and semantics.

An eventual proposal should come with implementation, but the first step is to design what we actually would want here.

1 Like

Although there is no built-in alternative, you can create one with built-in constructs. I have written about this with more detail on here.

3 Likes

I read your article, very insightful thank you

1 Like