Search code examples
javascriptreactive-cocoarxjs

Failable map in RxJS?


I'm from iOS land where I've used ReactiveCocoa extensively. In RAC, there is tryMap operator which sendError when the maping operation fails.

Is there an equivalent in Rx.JS? I can mimic the similar behavior using flatMap and another Observable but that certainly seems like an overkill.

Thanks!


Solution

  • I assume you want it to not end the stream when a mapping operation fails? I don't think RxJS it built in, but fairly easy to write. You just need to catch the error and have tryMap basically return an Either type of construct that is either an error or the mapping result:

    Rx.Observable.prototype.tryMap = function(selector) {
      var mapSelector = function(value, index, obs) {
        try {
          return {
            value: selector(value, index, obs)
          };
        } catch (e) {
          return {
            error: e
          };
        }
      };
      return this.map(mapSelector);
    };
    
    // Usage:
    Rx.Observable
      .of(1, 2, 3, 4, 5)
      .tryMap(function(v) {
        if ((v % 2) === 1) {
          throw new Error("odd numbers are evil");
        }
    
        return v / 2;
      })
      .subscribe(function(result) {
        if (result.error) {
          console.log("error: " + result.error.message);
        } else {
          console.log("result: " + result.value);
        }
      });
    <script src="https://getfirebug.com/firebug-lite-debug.js"></script>
    <script src="https://rawgit.com/Reactive-Extensions/RxJS/master/dist/rx.all.js"></script>