Ark.Paginator (ark v0.12.0)

Copy Markdown View Source

Summary

Functions

Accepts an initial state and a pagination callback and immediately calls the callback with the initial state, expecting a result tuple.

Types

paginator_fun()

@type paginator_fun() :: (state() ->
                      {:cont, Enumerable.t(), state()}
                      | {:halt, Enumerable.t()}
                      | {:error, term()})

state()

@type state() :: term()

Functions

stream(initial_state, callback)

@spec stream(state(), paginator_fun()) :: {:ok, Enumerable.t()} | {:error, term()}

Accepts an initial state and a pagination callback and immediately calls the callback with the initial state, expecting a result tuple.

If the callback returns {:cont, items, new_state}, then this function returns {:ok, stream}, otherwise it returns the same {:error, reason} tuple as the callback did.

The callback is intended to be a stream generator, so it can return one of the following:

  • {:cont, items, new_state}: Returns the items to be part of the stream, and a new state. The items can be a list, or a stream.
  • {:halt, items}: Returns the last items or stream and stops the pagination. The callback will not be called again.
  • {:error, reason}: Returns an error and stops the pagination. The stream will emit an error.

Example

iex> pages = %{1 => [1, 2, 3], 2 => [98, 99, 100]}
iex> {:ok, stream} =
iex>   Paginator.stream(1, fn
iex>     page ->
iex>       case Map.get(pages, page, []) do
iex>         [] -> {:halt, []}
iex>         items -> {:cont, items, page + 1}
iex>       end
iex>   end)
iex> Enum.to_list(stream)
[1, 2, 3, 98, 99, 100]