diff --git a/examples/alternate-receive/alternate_receive.bal b/examples/alternate-receive/alternate_receive.bal new file mode 100644 index 0000000000..b3503d8820 --- /dev/null +++ b/examples/alternate-receive/alternate_receive.bal @@ -0,0 +1,47 @@ +import ballerina/io; +import ballerina/lang.runtime; + +public function main() { + worker w1 { + 2 -> w3; + } + + worker w2 { + runtime:sleep(2); + 3 -> w3; + } + + worker w3 returns int { + // The value of the variable `result` is set as soon as the values from either + // worker `w1` or `w2` is received. + int result = <- w1 | w2; + return result; + } + + worker w4 returns error? { + int value = 10; + if value == 10 { + return error("Error in worker 1"); + } + value -> w6; + } + + worker w5 { + runtime:sleep(2); + 3 -> w6; + } + + worker w6 returns int|error? { + // Alternate receive action waits until a message that is not an error is received + // when error is not an expected static type. Since `w4` returns an error it + // waits further and sets the value that is received from `w5`. + int a = check <- w4 | w5; + return a; + } + + int valueW3 = wait w3; + io:println(valueW3); + + int|error? valueW6 = wait w6; + io:println(valueW6); +} diff --git a/examples/alternate-receive/alternate_receive.md b/examples/alternate-receive/alternate_receive.md new file mode 100644 index 0000000000..374b6519d3 --- /dev/null +++ b/examples/alternate-receive/alternate_receive.md @@ -0,0 +1,7 @@ +# Alternate receive + +The alternate receive action can be used to receive values from several workers. + +::: code alternate_receive.bal ::: + +::: out alternate_receive.out ::: diff --git a/examples/alternate-receive/alternate_receive.metatags b/examples/alternate-receive/alternate_receive.metatags new file mode 100644 index 0000000000..62f5262e77 --- /dev/null +++ b/examples/alternate-receive/alternate_receive.metatags @@ -0,0 +1,2 @@ +description: This BBE demonstrates the alternate receive action +keywords: ballerina, ballerina by example, bbe, worker, alternate receive diff --git a/examples/alternate-receive/alternate_receive.out b/examples/alternate-receive/alternate_receive.out new file mode 100644 index 0000000000..47036fd588 --- /dev/null +++ b/examples/alternate-receive/alternate_receive.out @@ -0,0 +1,3 @@ +$ bal run alternate_receive.bal +2 +3 diff --git a/examples/index.json b/examples/index.json index 5f3e2d7193..11061f8f68 100644 --- a/examples/index.json +++ b/examples/index.json @@ -1419,6 +1419,13 @@ "disableVerificationReason": "Includes varying output", "isLearnByExample": true }, + { + "name": "Alternate receive", + "url": "alternate-receive", + "verifyBuild": true, + "verifyOutput": true, + "isLearnByExample": true + }, { "name": "Multiple wait", "url": "multiple-wait",