Asynchronous sequences in F#
June 23, 2020
Some examples of working with asynchronous sequences in F# with the library FSharp.Control.AsyncSeq
:
Example #1
Given a function that fetches an item by id
asynchronously and a sequence of ids.
Goal: transform the ids into items : Async<'a list>
let getByIdsAsync (ids : int seq) (getById : int -> Async<'a>) : Async<'a list>=
ids
|> AsyncSeq.ofSeq // returns AsyncSeq<int>
|> AsyncSeq.mapAsync getById // returns AsyncSeq<'a>
|> AsyncSeq.toListAsync // returns Async<'a list>
Quick reference:
AsyncSeq.ofSeq
ofseq<'a> -> AsyncSeq<'a>
, create an asynchronous sequenceAsyncSeq.mapAsync
of(‘a -> Async<‘b>) -> AsyncSeq<‘a> -> AsyncSeq<‘b>
, maps each element toAsync
AsyncSeq.toListAsync
ofAsyncSeq<'a> -> Async<'a list>
, creates an async computation which iterates theAsyncSeq
and collects the output