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

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

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

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 am not sure how to write the contents of mergeMap . Is there any way to do this?

+5
source share
1 answer

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

Inside mergeMap you should 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())); }); 
+2
source

Source: https://habr.com/ru/post/1266219/


All Articles