Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to define a Task and not run it immediately?


let task = Task {
   await function(parameter: 2)
}

I would like to run this function inside the task some other time in the future. Is it possible to achieve this in Swift? Currently, function is executed immediately. My reason to do this is: pass multiple tasks to a function and run all of them at once using TaskGroup or some other approach.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My reason to do this is: pass multiple tasks to a function and run all of them at once using TaskGroup or some other approach.

Then you can just represent those un-run "tasks" as () async -> Void or () async -> SomeResultType. Your function can accept an array/vararg of those closures. Here is an example:

func someFunction(tasks: [() async -> Void]) async {

    // the function can decide to run these "tasks" with a task group, or do something else with them
    await withTaskGroup(of: Void.self) { group in
        for task in tasks {
            group.addTask {
                await task()
            }
        }
        await group.waitForAll()
    }
}

Usage:

await someFunction(tasks: [
    { await someAsyncFunction() },
    { await anotherAsyncFunction() },
    { ... }
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading