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

Time:01-13


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.

CodePudding user response:

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() },
    { ... }
])
  • Related