howto get task result with withDiscardingTaskGroup in Swift

73 views Asked by At

In Swift, withTaskGroup is used to get task completed data as:

let test1 = await withTaskGroup { grp in
    grp.addTask { "Task 1 data" }
    grp.addTask { "Task 2 data" }
}
         
for await result in grp {
    print(result) // got task completed data
}

How we can get data from task completed bywithDiscardingTaskGroup?

let test1 = await withDiscardingTaskGroup {grp in
    grp.addTask { "Task 1 data" }
    grp.addTask { "Task 2 data" }
}
1

There are 1 answers

0
Sweeper On BEST ANSWER

The whole point of DiscardingTaskGroup is to discard the results of child tasks. If you want results from child tasks, use a regular task group.

This is useful if the child tasks produce side effects, instead of returning values. The documentation says:

This [...] is best applied in situations where the result of a child task is some form of side-effect.

A discarding task group is kind of similar to a bunch of async lets of type Void:

async let sideEffect1: Void = doSomethingAsync1()
async let sideEffect2: Void = doSomethingAsync2()
async let sideEffect3: Void = doSomethingAsync3()
await [sideEffect1, sideEffect2, sideEffect3]

Of course, the main difference is that a task group can have a dynamic number of child tasks.


Side note: although the child tasks' results are discarded, the task group can still produce its own result, e.g.

let result = await withDiscardingTaskGroup(returning: Int.self) { group in
    // side effects...
    group.addTask { ... }
    group.addTask { ... }
    group.addTask { ... }

    // the group's own result
    return await getSomeIntegerAsynchronously()
}

getSomeIntegerAsynchronously will not wait for the child tasks to complete, and will run in parallel with the child tasks. withDiscardingTaskGroup however, will wait for all the child tasks, and also getSomeIntegerAsynchronously, to complete, before returning.