on master help sign in
Document "race" using exceptions
commitd9188336a366adc430b0ea6fba29b3868100687b authorHarendra Kumar <harendra.kumar@gmail.com> dateSat 27 Oct 2018, 01:17 (8 years ago) parenta615989
1 file changed+30−2
docs/streamly-vs-async.md+30−2
docs/streamly-vs-async.md+30−2
@@ -103,19 +103,47 @@ function:
103103
104104### race
105105
106−To run multiple actions and use the first result:
106+There are two ways to achieve the race functionality, using `take` or using
107+exceptions.
108+
109+#### `race` Using `take`
110+
111+We can run multiple actions concurrently and take the first result that
112+arrives:
107113
108114```haskell
109115 urls <- S.toList $ S.take 1 $ parallely $ getURL 1 |: getURL 2 |: S.nil
110116```
111117
112118After the first result arrives, the rest of the actions are canceled
113−automatically. You can take first `n` results as they arrive:
119+automatically. In general, we can take first `n` results as they arrive:
114120
115121```haskell
116122 urls <- S.toList $ S.take 2 $ parallely $ getURL 1 |: getURL 2 |: S.nil
117123```
118124
125+#### `race` Using Exceptions
126+
127+When an exception occurs in a concurrent stream all the concurrently running
128+actions are cacnceled on arrival of the exception. This can be used to
129+implement the race functionality. Each action in the stream can use an
130+exception to communicate the result. As soon as the first result arrives all
131+other actions will be canceled, for example:
132+
133+```haskell
134+ data Result = Result String deriving Show
135+ instance Exception Result
136+
137+ main = do
138+ url <- try $ runStream $ parallely $
139+ (getURL 2 >>= throwM . Result)
140+ |: (getURL 1 >>= throwM . Result)
141+ |: S.nil
142+ case url of
143+ Left (e :: SomeException) -> print e
144+ Right _ -> undefined
145+```
146+
119147### mapConcurrently
120148
121149There are many ways to map concurrently on a container and collect the results: