Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Observables / RxJS: How to make epic that returns different actions based on if / else?

I am trying to hook up my app with in app purchases using this: https://github.com/chirag04/react-native-in-app-utils

I have an epic where I want to emit success if it succeeds, and failure if it fails. Something like this:

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();
        }
      });
    });
};

However I'm not sure how to write the contents of mergeMap. Is there a way to do this?

like image 650
bigpotato Avatar asked Oct 18 '22 14:10

bigpotato


1 Answers

InAppUtils.purchaseProduct appears to use a Node-style callback. There is an RxJS static method that can be used to create an observable from such an API call: bindNodeCallback.

Within your mergeMap, you should be able to do something like this

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()));
});
like image 114
cartant Avatar answered Oct 21 '22 08:10

cartant