使用 RxJS 组合源事件和错误事件

Combining a source event and error event using RxJS

我在 Ionic 中使用来自 Cordova 插件 (https://github.com/mauron85/cordova-plugin-background-geolocation) 的 API,它允许您像这样订阅事件:

BackgroundGeolocation.on('location', (loc) => {
  // Handle location
});

BackgroundGeolocation.on('error', (error) => {
  // Handle error
});

我正在尝试将此接口包装到单个 Observable 中,以便我可以以常规方式订阅它并获取更新:

source.subscribe((loc) => {
  // handle location
}, (err) => {
  // handle error
})

我该怎么做?

我试过使用 fromEventPattern,我可以得到如下所示的 'location' 事件,但我也不确定如何添加错误。

const source = fromEventPattern(
  function addHandler(h) {
    return BackgroundGeolocation.on('location', (location) => {
      h(location);
    });
  }, function delHandler(h, signal) {
    signal.remove();
  }
);

您可以采取的一种方法是只使用 Observable.create。这是一个 StackBlitz 演示 (https://jsfiddle.net/4eLuvhkp/)。对于您的代码,它类似于...

const source = Observable.create(subscriber => {
  BackgroundGeolocation.on('location', (location) => {
    subscriber.next(location);
  });
  BackgroundGeolocation.on('error', (error) => {
    subscriber.error(error);
  });
  return () => {
    signal.remove();
  };
});

它可能只是 create 而不是 Observable.create,具体取决于您的导入样式。

编辑:添加了取消订阅处理程序。