asyncIters

Search:
Group by:
  Source

This package implements asynchronous iterators. For more information about asynchronous procedures in general, see std/asyncdispatch documentation.

Example:

import asyncIters
# `async`, `await`, and `std/asyncfutures` are imported as well.
from   std/asyncdispatch import sleepAsync, waitFor

func countUpAsync(a, b: int): AsyncIterator[int] =
  iterator countUpAsync: Future[int] {.asyncIter.} =
    for i in a .. b:
      echo "Generating..."
      await sleepAsync 50 # You can await.
      yieldAsync i        # And you can yield.

  result = countUpAsync

proc test {.async.} =
  for i in awaitIter countUpAsync(1, 5):
    echo "Received ", i
    await sleepAsync 150

waitFor test()

Types

AsyncIterator[T] = the customAsyncIterator(T, Future)

Type of async iterators after they are processed.

This type is not declared if you pass -d=asyncBackend:none (or some unrecognized backend name) to the compiler. Known backends include asyncdispatch (used by default if not set explicitly) and chronos. If you’d like to use asyncIters with a backend that did not exist at the moment of writing, you need to use customAsyncIterator and specify some Future-like type.

Note also that this is only a suggested iterator type. Nothing stops you from using a different one or even having multiple in the same program.

  Source

Macros

macro asyncIter(iterDef: untyped): untyped

Define an async iterator. It can have yieldAsync and yieldAsyncFrom statements in its body.

This macro can be applied to either individual iterator definitions ({.asyncIter.}) or entire sections of code containing them (asyncIter:).

  Source
macro awaitIter(loop: ForLoopStmt)
Iterate over an async iterator. Like regular await, this can only occur in procedures marked with {.async.} or {.asyncIter.}.   Source
macro yieldAsync(values: varargs[typed]): untyped {....deprecated: "enclose multiple values in parentheses to yield them as a tuple".}
Deprecated: enclose multiple values in parentheses to yield them as a tuple
Transfer control to the caller of the async iterator. If several values are passed, they are wrapped in a tuple.   Source

Templates

template customAsyncIterator(T, fut: typed): type
Type of async iterators after they are processed. T is the type of values an iterator yields; fut is the future type constructor those values are wrapped with. The only requirement is that fut must be instantiable with one generic parameter (i.e., fut[U]).   Source
template yieldAsync(phantom: Inaccessible) {.
    error: "congratulations, you\'ve found a way to invoke me".}
  Source