2

我正在使用 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);
4

1 回答 1

3

好吧,我从来没有使用过,redux-observable但我认为你有很多merge调用,而你不需要它们,因为你没有使用它们传递给回调的值。我个人更喜欢 usign concat,因为很明显你想从 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)所以我假设他们不返回 Observables(尽管他们的fetch*前缀)。

此外,您真的需要showLoading()hideLoading()返回要重新发送的值和链的一部分吗?

于 2016-11-04T11:25:01.823 回答