我正在使用 react-observable 来编排我的应用程序中的 AJAX 调用。我已经连接了 react-redux-loading-bar 以在 AJAX 调用开始时显示一个加载栏,并在它们完成时隐藏它。它有效,但感觉不是很“干净”。
有没有更好的方法来利用 RXJS 或 redux-observable 来使这个更干净?
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);