Redux Observables / RxJS:如何制作基于if / else返回不同​​动作的史诗?

时间:2017-04-02 04:18:26

标签: rxjs redux-observable

我正在尝试使用以下应用程序购买我的应用程序:https://github.com/chirag04/react-native-in-app-utils

我有一个史诗,如果它成功我想要发出成功,如果它失败则失败。像这样:

import 'rxjs';
import { InAppUtils } from 'NativeModules';

import * as packagesActions from '../ducks/packages';
import * as subscriptionActions from '../ducks/subscription';

export default function createSubscription(action$, store) {
  return action$.ofType(packagesActions.SELECT)
    .mergeMap(action => {
      const productId = action.payload;
      InAppUtils.purchaseProduct(productId, (error, response) => {
        if(response && response.productIdentifier) {
          return subscriptionActions.subscribeSuccess();
        } else {
          return subscriptionActions.subscribeFailure();
        }
      });
    });
};

但我不确定如何撰写mergeMap的内容。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

InAppUtils.purchaseProduct似乎使用了Node样式的回调。有一个RxJS静态方法可用于从这样的API调用创建一个observable:bindNodeCallback

mergeMap内,您应该能够做到这样的事情

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/bindNodeCallback';
import 'rxjs/add/observable/of';

...
.mergeMap(action => {
  const productId = action.payload;
  const bound = Observable.bindNodeCallback((callback) => InAppUtils.purchaseProduct(productId, callback));
  return bound()
    .map(response => subscriptionActions.subscribeSuccess())
    .catch(error => Observable.of(subscriptionActions.subscribeFailure()));
});