【发布时间】:2019-08-08 17:02:15
【问题描述】:
Redux 似乎是一个非常适合移动应用程序开发的架构。但是,移动应用具有一些 Web 应用不常见的功能。
就我而言,我想在某个特定屏幕启动后开始长轮询/监控位置/跟踪文件系统(任何监视某些外部状态的操作),并在屏幕关闭时停止。
假设我们有一个函数,它可以随着时间的推移发出多个事件。
Stream<Event>monitor();
我只想在某些特定屏幕处于活动状态时收听该功能。
最好的方法是什么?
【问题讨论】:
Redux 似乎是一个非常适合移动应用程序开发的架构。但是,移动应用具有一些 Web 应用不常见的功能。
就我而言,我想在某个特定屏幕启动后开始长轮询/监控位置/跟踪文件系统(任何监视某些外部状态的操作),并在屏幕关闭时停止。
假设我们有一个函数,它可以随着时间的推移发出多个事件。
Stream<Event>monitor();
我只想在某些特定屏幕处于活动状态时收听该功能。
最好的方法是什么?
【问题讨论】:
假设您有 3 个页面:'PageHome.dart'、'Page1.dart'、'Page2.dart'。
创建另一个 dart 文件 'GlobalVariables.dart',在该文件中创建一个类 gv,为三个页面创建静态 redux 'stores'。
在 gv 中创建静态 var strCurPage。
假设每个页面都有一个要被外部事件更改的变量,在 gv 中也将它们声明为静态变量。
GlobalVariables.dart 中的代码:
import 'package:redux/redux.dart';
enum Actions {
Increment
}
// The reducer, which takes the previous count and increments it in response to an Increment action.
int reducerRedux(int intSomeInteger, dynamic action) {
if (action == Actions.Increment) {
return intSomeInteger + 1;
}
return intSomeInteger;
}
class gv {
static Store<int> storePageHome =
new Store<int>(reducerRedux, initialState: 0);
static Store<int> storePage1 =
new Store<int>(reducerRedux, initialState: 0);
static Store<int> storePage2 =
new Store<int>(reducerRedux, initialState: 0);
static String strCurPage = 'PageHome';
static String strPageHomeVar = 'PageHomeInitialContent';
static String strPage1Var = 'Page1InitialContent';
static String strPage2Var = 'Page2InitialContent';
}
在所有其他 dart 文件中导入“GlobalVariables.dart”。
在导航到新页面之前,例如从PageHome到Page1,设置:
gv.strCurPage = 'Page1';
void thisFunctionCalledByExternalEvent(strPage1NewContent, strPage2NewContent) {
gv.strPage1Var = strPage1NewContent;
gv.strPage2Var = strPage2NewContent;
if (gv.strCurPage == 'Page1') {
// Dispatch storePage1 to refresh Page 1
storePage1.dispatch(Actions.Increment);
} else if (gv.strCurPage == 'Page2') {
// Dispatch storePage2 to refresh Page 2
storePage2.dispatch(Actions.Increment);
} else {
// Do not need to refresh page if user currently navigating other pages.
// so do nothing here
}
}
我不知道这是否是最好的方法,但是使用 redux 和 GlobalVariables.dart,我可以:
知道用户当前正在浏览哪个页面。
即使在事件触发时用户不在该页面时,也可以更改页面的内容。 (但内容会在用户稍后导航到该页面时显示)
当事件触发时,无论用户正在浏览哪个页面,都强制用户转到特定页面。
【讨论】: