diff --git a/lib/core/task.toit b/lib/core/task.toit index 2279ae70d..39f09a16d 100644 --- a/lib/core/task.toit +++ b/lib/core/task.toit @@ -90,16 +90,36 @@ interface Task: return also throws. If $required is less than the number of $lambdas, the - method returns when $required tasks have completed. + method returns when $required tasks have completed. If $required + is equal to 0, the method returns immediately. + + # Examples + ``` + results := Task.group [ + :: 42, + :: 87, + ] + print results // => {0: 42, 1: 87}. + + results = Task.group --required=1 [ + // Due to the required=1, this lambda will be aborted, once + // the lambda returning 42 has finished. + :: sleep --ms=1_000; 87, + :: 42, + ] + print results // => { 1: 42 }. + ``` */ static group lambdas/List -> Map --required/int=lambdas.size: count ::= lambdas.size tasks ::= Array_ count results ::= {:} - if count < 2 or not (1 <= required <= count): + if not (0 <= required <= count): throw "Bad Argument" + if required == 0: return results + is-stopping/bool := false is-canceled/bool := false caught/Exception_? := null diff --git a/tests/task-group-test.toit b/tests/task-group-test.toit index 9223db412..a30ea59d0 100644 --- a/tests/task-group-test.toit +++ b/tests/task-group-test.toit @@ -31,20 +31,27 @@ run-case lambda/Lambda -> Task: return child test-simple: + expect-structural-equals {:} (Task.group []) + + expect-structural-equals { 0: 42 } (Task.group [ + :: 42, + ]) + expect-structural-equals { 0: 42, 1: 87 } (Task.group [ :: 42, :: 87, ]) test-bad-arguments: - expect-throw "Bad Argument": (Task.group []) - expect-throw "Bad Argument": (Task.group [ :: 42 ]) expect-throw "Bad Argument": (Task.group --required=-1 [ :: 42, :: 87 ]) - expect-throw "Bad Argument": (Task.group --required= 0 [ :: 42, :: 87 ]) expect-throw "Bad Argument": (Task.group --required= 3 [ :: 42, :: 87 ]) expect-throw "Bad Argument": (Task.group --required= 9 [ :: 42, :: 87 ]) test-required: + expect-structural-equals {:} (Task.group --required=0 [ + :: 42, + :: sleep --ms=1_000; 87, + ]) expect-structural-equals { 0: 42 } (Task.group --required=1 [ :: 42, :: sleep --ms=1_000; 87,