Rxjs 在史诗中观察到的流的开始和结束时发出动作的最佳实践方法?
我正在使用react observable来协调应用程序中的AJAX调用。我连接了react-redux加载栏,在AJAX调用开始时显示加载栏,在调用结束时隐藏加载栏。它能工作,但感觉不太“干净” 有没有更好的方法来利用RXJS或redux observable使其更干净Rxjs 在史诗中观察到的流的开始和结束时发出动作的最佳实践方法?,rxjs,redux-observable,Rxjs,Redux Observable,我正在使用react observable来协调应用程序中的AJAX调用。我连接了react-redux加载栏,在AJAX调用开始时显示加载栏,在调用结束时隐藏加载栏。它能工作,但感觉不太“干净” 有没有更好的方法来利用RXJS或redux observable使其更干净 import Rx from "rxjs"; import {combineEpics} from "redux-observable"; import client from "../../integration/rest/
import Rx from "rxjs";
import {combineEpics} from "redux-observable";
import client from "../../integration/rest/client";
import {showLoading, hideLoading} from 'react-redux-loading-bar'
import * as types from "./actionTypes";
import * as actions from "./actions";
const fetchEpic = action$ =>
action$.ofType(types.FETCH)
.mergeMap(action =>
Rx.Observable.of(showLoading()).merge(
client({method: 'GET', path: '/api'})
.mergeMap(payload => Rx.Observable.of(actions.fetchSuccess(payload), hideLoading()))
.catch(error => Rx.Observable.of(actions.fetchFailure(error), hideLoading()))
)
);
export default combineEpics(fetchEpic);
更新:
在研究了Martin关于使用concat的建议后,我附上了一个简化版,我很满意
import Rx from "rxjs";
import {combineEpics} from "redux-observable";
import client from "../../integration/rest/client";
import {showLoading, hideLoading} from 'react-redux-loading-bar'
import * as types from "./actionTypes";
import * as actions from "./actions";
const fetchEpic = action$ =>
action$.ofType(types.FETCH)
.mergeMap(action =>
Rx.Observable.merge(
Rx.Observable.of(showLoading()),
client({method: 'GET', path: '/api'})
.map(payload => actions.fetchSuccess(payload))
.catch(error => Rx.Observable.of(actions.fetchFailure(error)))
.concat(Rx.Observable.of(hideLoading()))
)
);
export default combineEpics(fetchEpic);
嗯,我从未使用过
redux observable
,但我认为您有很多merge
调用,而您不需要它们,因为您没有使用它们传递给回调的值。我个人更喜欢usignconcat
,因为很明显,您希望按顺序从Obseravbles发出值:
const fetchEpic = action$ =>
action$.ofType(types.FETCH)
.startWith(showLoading())
.concat(client({method: 'GET', path: '/api'})
.concatMap(payload => Rx.Observable.of(actions.fetchSuccess(payload)))
.catch(error => Rx.Observable.of(actions.fetchFailure(error)))
)
.concat(Rx.Observable.of(hideLoading())
);
我不知道什么是actions.fetchSuccess(payload)
或actions.fetchFailure(error)
,所以我假设它们不返回可观察对象(显示它们的fetch*
前缀)
另外,您真的需要
showLoading()
和hideLoading()
返回要重新提交的值以及链的一部分吗?您的示例对redux observable不太有效,但您关于查看concat的建议正是我需要简化它的地方。我将发布更新版本并将其标记为答案;假设在一天结束之前没有其他人能胜过你的建议。