redux_saga library

redux_saga is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, easy to test, and better at handling failures.

Classes

ActionChannel
Creates an effect that instructs the middleware to queue the actions matching pattern using an event channel. Optionally, you can provide a buffer to control buffering of the queued actions.
All
Creates an Effect description that instructs the middleware to run multiple Effects in parallel and wait for all of them to complete.
AllResult
Result of an All effect
Apply
An alias for Call effect.
BasicChannel
A basic channel implementation.
Buffer<T>
Used to implement the buffering strategy for a channel.
Buffers
Provides some common buffers.
Call
Creates an Effect description that instructs the middleware to call the function fn with args and namedArgs as arguments.
Cancel
If tasks provided then creates an Effect description that instructs the middleware to cancel a previously forked tasks, otherwise creates an Effect description that instructs the middleware to cancel a task in which it has been yielded (self-cancellation). Self-cancellation allows to reuse destructor-like logic inside a Finally blocks.
Cancelled
Creates an effect that instructs the middleware to return whether this generator has been cancelled. Typically you use this Effect in a finally block to run Cancellation specific code.
Channel<T>
A channel is an object used to send and receive messages between tasks. Messages from senders are queued until an interested receiver request a message, and registered receiver is queued until a message is available.
CloneableGenerator
Takes a generator function (sync*) and returns a generator function. All generators instantiated from this function will be cloneable. For testing purpose only.
CPS
Creates an Effect description that instructs the middleware to invoke fn as a Node style function.
CPSCallback
CPS effect callback object. Provides callback and self-cancellation cancel callback.
Delay
Returns an effect descriptor to block execution for duration and return value.
Effect
Base Saga effect type. All effects are inherited from this class.
EffectWithResult
Base class for effects returning a value.
EndAction
End action class
EventChannel
Creates channel that will subscribe to an event source using the subscribe method. Incoming events from the event source will be queued in the channel until interested takers are registered.
FlushChannel
Creates an effect that instructs the middleware to flush all buffered items from the channel. Flushed items are returned back to the saga, so they can be utilized if needed.
Fork
Creates an Effect description that instructs the middleware to perform a non-blocking call on fn
FutureWithCancel
Cancellable Future.
GetContext
Creates an effect that instructs the middleware to return a specific property of saga's context.
Join
Creates an Effect description that instructs the middleware to wait for the result of a previously forked tasks.
JoinResult
Result of an Join effect
MockTask
Creates an object that mocks a Task for testing purposes only
MultiCastChannel
A channel type for handling actions/events in most cases. There may be more than one takers awaiting the channel. It does not buffer messages if there is no takers awaiting. Any message without any takers will be lost.
Options
Optional parameters can be passed to middleware creation.
Put
Creates an Effect description that instructs the middleware to schedule the dispatching of an action to the store. This dispatch may not be immediate since other tasks might lie ahead in the saga task queue or still be in progress.
PutResolve
Same as Put effect. Only resolve is true by default.
Race
Creates an Effect description that instructs the middleware to run a Race between multiple Effects.
RaceResult
Result of a Race Effect
Result<T>
Result value of an Effect after resolved. It keeps data on value.
Return
Returns from a Generator function like a return statement in a normal function. Generator stops to instruct remaining statements and immediately returns with the provided resultValue value.
SagaAction
An optional base class/interface for actions
SagaContext
Manages saga context. Context is basically a key/value dictionary stored in objects member of class. Middleware creates and manages context by instantiating SagaContext.
SagaMeta
Meta info for saga. If name is not provided then id is used to identify a saga.
SagaMiddleware
Middleware class that runs Sagas. It is an abstract class. To instantiate a middleware use createSagaMiddleware helper function.
SagaMonitor
Used by the middleware to dispatch monitoring events. Actually the middleware dispatches 6 events:
Select
Creates an effect that instructs the middleware to invoke the provided selector on the current Store's state (i.e. returns the result of selector(getState(), args: [...])).
SetContext
Creates an effect that instructs the middleware to update its own context. This effect extends saga's context instead of replacing it.
Spawn
Same as Fork but creates a detached task. A detached task remains independent from its parent and acts like a top-level task. The parent will not wait for detached tasks to terminate before returning and all events which may affect the parent or the detached task are completely independents (error, cancellation).
StdChannel
Default channel type that middleware using to handle messages. It has the same behaviour like MultiCastChannel. In most cases this class can be used to handle messages.
Take
Creates an Effect description that instructs the middleware to wait for a specified action on the Store or if provided on the channel. The Generator is suspended until an action that matches pattern is dispatched.
TakeCallback<T>
A callback class containing callback functions to handle Channel.take
TakeMaybe
Same as Take but does not automatically terminate the Saga on an End action. Instead all Sagas blocked on a take Effect will get the End object.
Task<T>
The Task interface specifies the result of running a Saga using Fork, SagaMiddleware.run
TaskResult
Represents possible result of a Task
Try
An alias for Call effect. It makes try/catch/finally code blocks more readable.
TryReturn
An alias for Try/Call effect. It makes try/catch/finally code blocks more readable and returns value like Return. If you want to return from a returned value from a Try/Catch/Finally block then use TryReturn.

Properties

End EndAction
End action
final
sagaError SagaError
Global instance of SagaError. It is used to rethrow error on Catch block. Use throw sagaError; to rethrow error on Catch.
final
TaskCancel TaskResult
Result value for a cancelled Task
final
Terminate TaskResult
Result value for a terminated Task
final

Functions

applyMiddleware<State>(SagaMiddleware middleware) → Middleware<State>
Connects the middleware to the Redux Store
asap(TaskCallback task) → void
Executes or queues a task depending on the state of the scheduler (suspended or released)
createSagaMiddleware([Options? options]) SagaMiddleware
Creates a Redux middleware
createTestMiddleware([Options? options]) SagaMiddleware
Creates middleware for test purposes
Debounce(Function saga, {List? args, Map<Symbol, dynamic>? namedArgs, Function? Catch, Function? Finally, Channel? channel, dynamic pattern, Duration? duration, bool detached = false, String? name, Result? result}) Fork
Spawns a saga on an action dispatched to the Store or the channel provided that matches pattern. Saga will be called after it stops taking pattern actions for duration. Purpose of this is to prevent calling saga until the actions are settled off.
immediately(TaskCallbackImmediately task) Task
Puts the scheduler in a suspended state and executes a task immediately.
isEnd(dynamic action) bool
Checks whether an action is End action
isSagaDispatchedAction(dynamic action) bool
Checks whether an action is dispatched by a Saga before
isSagaError(dynamic e) bool
Checks whether error e or e.message is a SagaError
Retry(Function fn, {List? args, Map<Symbol, dynamic>? namedArgs, Function? Catch, Function? Finally, int? maxTries, Duration? duration, String? name, Result? result}) Call
Creates an Effect description that instructs the middleware to call the function fn with args and namedArgs as arguments. In case of failure will try to make another call after a duration, if a number of attempts < maxTries.
TakeEvery(Function saga, {List? args, Map<Symbol, dynamic>? namedArgs, Function? Catch, Function? Finally, Channel? channel, dynamic pattern, bool detached = false, String? name, Result? result}) Fork
Spawns a saga on each action dispatched to the Store or the channel provided that matches pattern.
TakeLatest(Function saga, {List? args, Map<Symbol, dynamic>? namedArgs, Function? Catch, Function? Finally, Channel? channel, dynamic pattern, bool detached = false, String? name, Result? result}) Fork
Forks a saga on each action dispatched to the Store or the channel provided that matches pattern. And automatically cancels any previous saga task started previously if it's still running.
TakeLeading(Function saga, {List? args, Map<Symbol, dynamic>? namedArgs, Function? Catch, Function? Finally, Channel? channel, dynamic pattern, bool detached = false, String? name, Result? result}) Fork
Spawns a saga on each action dispatched to the Store or the channel provided that matches pattern. After spawning a task once, it blocks until spawned saga completes and then starts to listen for a pattern again.
Throttle(Function saga, {List? args, Map<Symbol, dynamic>? namedArgs, Function? Catch, Function? Finally, Channel? channel, dynamic pattern, Duration? duration, bool detached = false, String? name, Result? result}) Fork
Spawns a saga on an action dispatched to the Store or the channel provided that matches pattern. After spawning a task it's still accepting incoming actions into the underlying buffer, keeping at most 1 (the most recent one), but in the same time holding up with spawning new task for duration (hence its name - Throttle). Purpose of this is to ignore incoming actions for a given period of time while processing a task.

Typedefs

Callback = void Function()
Void callback function handler
CPSCallbackHandler = void Function({dynamic err, dynamic res})
CPSCallback handler member used for CPS effect.
DataCallback<T> = void Function(T? message)
Invoked after a successfull taken message
DispatchHandler = dynamic Function(dynamic action)
Handler to dispatch actions to store
EffectMiddlewareHandler = void Function(dynamic effect, NextMiddlewareHandler next)
Handler for creating custom effects for middleware. It can be passed as an option while creating middleware. Effects middleware intercepts messages before they reach to middleware.
Emit<T> = void Function(T message)
Handler for emitting value to EventChannel
GetStateHandler = dynamic Function()
Handler to get store state
NextMiddlewareHandler = void Function(dynamic effect)
Handler for a passing effect to next middleware.
OnErrorHandler = void Function(dynamic e, String stack)
Handler for catching uncaught errors. It can be passed as an option while creating middleware.
PatternMatcher<T> = bool Function(T message)
Matcher type for matching messages on a channel using Take effect.
Subscribe<T> = Unsubscribe Function(Emit<T> emitter)
Handler for subscribe to EventChannel. It must return an Unsubscribe handler to unsubscribe channel.
TaskCallback = void Function()
Defines a scheduler task to queue
TaskCallbackImmediately = Task Function()
Defines a scheduler task to execute immediately
Unsubscribe = void Function()
Handler for unsubscribe from EventChannel

Exceptions / Errors

BufferisEmpty
Thrown when an unexpected access to an empty buffer. Check before accessing to buffer if there is any items buffered
BufferOverflow
Thrown when buffer overflows
CallbackCannotBeNull
Thrown when a null callback provided
CannotDetermineNullFunctionArguments
Thrown when provided function is null
CannotDetermineNullFunctionReturnType
Thrown when provided function is null
ClosedChannelWithTakers
Thrown when there is pending takers on a closed channel
EventChannelMustReturnUnsubscribeFunction
Thrown when a subscribe does not provide unsubscribe on return for an EventChannel
GeneratorFunctionExpectedException
Thrown when provided function is not a generator function
InvalidOperation
Thrown on an invalid operation
InvalidPattern
Thrown when Take effects matcher pattern is invalid
NullInputError
Thrown when a saga or channel provided with a null action
PendingTakersWithNotEmptyBuffer
Thrown when there is pending takers on a non-empty buffer
SagaError
Caught error type at Catch block. No need to instantiate. Use global instance sagaError instead. Use throw sagaError; to rethrow error on Catch block.
SagaFunctionMustBeGeneratorException
Thrown when a non-generator function is passed to the middlewares SagaMiddleware.run method. Saga must have a return type of Iterable.
SagaFunctionMustBeNonNullException
Thrown when a null function is passed to the middlewares SagaMiddleware.run method
SagaMiddlewareDispatchMustBeSet
Thrown when SagaMiddleware.dispatch property is null By default it is set properly after SagaMiddleware.setStore
SagaMiddlewareGetStateMustBeSet
Thrown when SagaMiddleware.getState property is null By default it is set properly after SagaMiddleware.setStore
SagaMustBeConnectedToTheStore
Thrown when the middleware tries to run a saga before connected to a store via applyMiddleware
SagaStoreCanNotBeNull
Thrown when SagaMiddleware.setStore store argument is passed null
SagaStoreMustBeSet
Thrown when the middleware tries to run a saga before store property set via SagaMiddleware.setStore