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>=
    |> AsyncSeq.ofSeq             // returns AsyncSeq<int>
    |> AsyncSeq.mapAsync getById  // returns AsyncSeq<'a>
    |> AsyncSeq.toListAsync       // returns Async<'a list>

Quick reference:

  • AsyncSeq.ofSeq of seq<'a> -> AsyncSeq<'a>, create an asynchronous sequence
  • AsyncSeq.mapAsync of (‘a -> Async<‘b>) -> AsyncSeq<‘a> -> AsyncSeq<‘b>, maps each element to Async
  • AsyncSeq.toListAsync of AsyncSeq<'a> -> Async<'a list>, creates an async computation which iterates the AsyncSeq and collects the output