Course of Raku / Functional, concurrent, reactive, and web programming / Reactive programming / react and whenever / Exercises / Two whenevers

Solution: Two whenevers

Here is a possible solution to the task.

Code

my $sum = 0;

react {
    whenever Supply.from-list(5, 10) {
        $sum += $_;
    }
    whenever Supply.from-list(100, 200) {
        $sum += $_;
    }
}

say $sum;

🦋 You can find the source code in the file two-whenevers.raku.

Output

315

Comments

  1. Each whenever watches its own supply; both add their values to the same $sum.

  2. The react block finishes only when both supplies are done, so $sum holds 15 + 300, that is 315. Because we only sum, the order in which the two streams interleave does not matter.

Course navigation

Two whenevers   |   await