transferHandlers.ts 923 B

123456789101112131415161718192021222324252627
  1. import * as comlink from 'comlink';
  2. import { Subscriber } from 'rxjs';
  3. // Observers, ie. functions passed to `observable.subscribe(...)`, are converted to a subclass of `Subscriber` before they are sent to the source Observable.
  4. // The conversion happens internally in the RxJS library - this transfer handler is catches them and wraps them with a proxy
  5. const subscriberTransferHandler: any = {
  6. canHandle(value: any): boolean {
  7. return value && value instanceof Subscriber;
  8. },
  9. serialize(value: Function): [MessagePort, Transferable[]] {
  10. const obj = comlink.proxy(value);
  11. const { port1, port2 } = new MessageChannel();
  12. comlink.expose(obj, port1);
  13. return [port2, [port2]];
  14. },
  15. deserialize(value: MessagePort): comlink.Remote<MessagePort> {
  16. value.start();
  17. return comlink.wrap<MessagePort>(value);
  18. },
  19. };
  20. comlink.transferHandlers.set('SubscriberHandler', subscriberTransferHandler);