redux_epics 是一个用于 redux.dart 状态管理库的中间件,通过响应式流实现副作用处理。它允许开发者使用 Dart 的 Stream API 以声明式和可测试的方式管理异步操作(如 API 调用或导航)。通过与 Redux 的 dispatch 机制集成,确保副作用在状态管理流程中被清晰地协调。该包特别适用于需要通过外部交互实现可预测状态转换的复杂应用。
适合场景
处理 HTTP 请求
管理导航流程
异步处理用户事件
实现实时数据更新
与外部服务同步状态
主要特点
基于流的副作用处理
与 redux.dart 的集成
声明式效果组合
可测试且可重用的史诗
支持错误处理和重试
适合对象
复杂的状态管理需求
具有大量异步逻辑的应用程序
偏好函数式响应模式的团队
使用 redux.dart 的项目已存在
寻求清晰关注点分离的开发者
使用建议
需要理解 Streams 和 Rx
为简单应用增加复杂性
需要仔细设计错误处理
与其他替代方案相比,文档有限
初学者的学习曲线更陡峭
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
Redux Epics
Redux is great for synchronous
updates to a store in response to actions. However, working with complex
asynchronous operations, such as autocomplete search experiences, can be a bit
tricky with traditional middleware. This is where Epics come in!
The best part: Epics are based on Dart Streams. This makes routine tasks easy,
and complex tasks such as asynchronous error handling, cancellation, and
debouncing a breeze.
Note: For users unfamiliar with Streams, simple async cases are easier to handle
with a normal Middleware Function. If normal Middleware Functions or
Thunks work for you, you're
doing it right! When you find yourself dealing with more complex scenarios,
such as writing an Autocomplete UI, check out the Recipes below to see how
Streams / Epics can make your life easier.
Example
Let's say your app has a search box. When a user submits a search term, you
dispatch a PerformSearchAction which contains the term. In order to actually
listen for the PerformSearchAction and make a network request for the results,
we can create an Epic!
In this instance, our Epic will need to filter all incoming actions it receives
to only the Action it is interested in: the PerformSearchAction. This will
be done using the where method on Streams. Then, we need to make a network
request with the search term using asyncMap method. Finally, we need to
transform those results into an action that contains the search results. If an
error has occurred, we'll want to return an error action so our app can respond
accordingly.
Here's what the above description looks like in code.
import'dart:async';
import'package:redux_epics/redux_epics.dart';
Stream<dynamic> exampleEpic(Stream<dynamic> actions, EpicStore<State> store) {
return actions
.where((action) => action isPerformSearchAction)
.asyncMap((action) =>
// Pseudo api that returns a Future of SearchResults
api.search((action asPerformSearch).searchTerm)
.then((results) => SearchResultsAction(results))
.catchError((error) => SearchErrorAction(error)));
}
Connecting the Epic to the Redux Store
Now that we've got an epic to work with, we need to wire it up to our Redux
store so it can receive a stream of actions. In order to do this, we'll employ
the EpicMiddleware.
import'package:redux_epics/redux_epics.dart';
import'package:redux/redux.dart';
var epicMiddleware = newEpicMiddleware(exampleEpic);
var store = newStore<State>(fakeReducer, middleware: [epicMiddleware]);
Combining epics and normal middleware
To combine the epic Middleware and normal middleware, simply use both in the
list! Note: You may need to provide
var store = newStore<AppState>(
fakeReducer,
middleware: [myMiddleware, EpicMiddleware<AppState>(exampleEpic)],
);
If you're combining two Lists, please make sure to use the + or the ...
spread operator.
var store = newStore<AppState>(
fakeReducer,
middleware: [myMiddleware] + [EpicMiddleware<AppState>(exampleEpic)],
);
Combining Epics
Rather than having one massive Epic that handles every possible type of action,
it's best to break Epics down into smaller, more manageable and testable units.
This way we could have a searchEpic, a chatEpic, and an updateProfileEpic,
for example.
However, the EpicMiddleware accepts only one Epic. So what are we to do? Fear
not: redux_epics includes class for combining Epics together!
import'package:redux_epics/redux_epics.dart';
final epic = combineEpics<State>([
searchEpic,
chatEpic,
updateProfileEpic,
]);
Advanced Recipes
In order to perform more advanced operations, it's often helpful to use a
library such as RxDart.
Casting
In order to use this library effectively, you generally need filter down to
actions of a certain type, such as PerformSearchAction. In the previous
examples, you'll noticed that we need to filter using the where method on the
Stream, and then manually cast (action as SomeType) later on.
To more conveniently narrow down actions to those of a certain type, you have
two options:
TypedEpic
The first option is to use the built-in TypedEpic class. This will allow you
to write Epic functions that handle actions of a specific type, rather than all
actions!
final epic = newTypedEpic<State, PerformSearchAction>(searchEpic);
Stream<dynamic> searchEpic(
// Note: This epic only handles PerformSearchActionsStream<PerformSearchAction> actions,
EpicStore<State> store,
) {
return actions
.asyncMap((action) =>
// No need to cast the action to extract the search term!
api.search(action.searchTerm)
.then((results) => SearchResultsAction(results))
.catchError((error) => SearchErrorAction(error)));
}
RxDart
You can use the whereType method provided by RxDart. It will both perform a
where check and then cast the action for you.
import'package:redux_epics/redux_epics.dart';
import'package:rxdart/rxdart.dart';
Stream<dynamic> ofTypeEpic(Stream<dynamic> actions, EpicStore<State> store) {
// Wrap our actions Stream as an Observable. This will enhance the stream with// a bit of extra functionality.return actions
// Use `whereType` to narrow down to PerformSearchAction
.whereType<PerformSearchAction>()
.asyncMap((action) =>
// No need to cast the action to extract the search term!
api.search(action.searchTerm)
.then((results) => SearchResultsAction(results))
.catchError((error) => SearchErrorAction(error)));
}
Cancellation
In certain cases, you may need to cancel an asynchronous task. For example, your
app begins loading data in response to a user clicking on a the search button by
dispatching a PerformSearchAction, and then the user hit's the back button in
order to correct the search term. In that case, your app dispatches a
CancelSearchAction. We want our Epic to cancel the previous search in
response to the action. So how can we accomplish this?
This is where Observables really shine. In the following example, we'll employ
Observables from the RxDart library to beef up the power of streams a bit, using
the switchMap and takeUntil operator.
import'package:redux_epics/redux_epics.dart';
import'package:rxdart/rxdart.dart';
Stream<dynamic> cancelableSearchEpic(
Stream<dynamic> actions,
EpicStore<State> store,
) {
return actions
.whereType<PerformSearchAction>()
// Use SwitchMap. This will ensure if a new PerformSearchAction// is dispatched, the previous searchResults will be automatically // discarded.//// This prevents your app from showing stale results.
.switchMap((action) {
returnStream.fromFuture(api.search(action.searchTerm)
.then((results) => SearchResultsAction(results))
.catchError((error) => SearchErrorAction(error)))
// Use takeUntil. This will cancel the search in response to our// app dispatching a `CancelSearchAction`.
.takeUntil(actions.whereType<CancelSearchAction>());
});
}
Autocomplete using debounce
Let's take this one step further! Say we want to turn our previous example into
an Autocomplete Epic. In this case, every time the user types a letter into the
Text Input, we want to fetch and show the search results. Each time the user
types a letter, we'll dispatch a PerformSearchAction.
In order to prevent making too many API calls, which can cause unnecessary load
on your backend servers, we don't want to make an API call on every single
PerformSearchAction. Instead, we'll wait until the user pauses typing for a
short time before calling the backend API.
We'll achieve this using the debounce operator from RxDart.
import'package:redux_epics/redux_epics.dart';
import'package:rxdart/rxdart.dart';
Stream<dynamic> autocompleteEpic(
Stream<dynamic> actions,
EpicStore<State> store,
) {
return actions
.whereType<PerformSearchAction>()
// Using debounce will ensure we wait for the user to pause for // 150 milliseconds before making the API call
.debounce(newDuration(milliseconds: 150))
.switchMap((action) {
returnStream.fromFuture(api.search(action.searchTerm)
.then((results) => SearchResultsAction(results))
.catchError((error) => SearchErrorAction(error)))
.takeUntil(actions.whereType<CancelSearchAction>());
});
}
Dependency Injection
Dependencies can be injected manually with either a Functional or an Object-Oriented style. If you choose, you may use a Dependency Injection or Service locator library as well.
In production code the epics can be created at the point where combineEpics is called. If you're using separate main_<environment>.dart files to configure your application for different environments you may want to pass the config to the RealWebService at this point.