Coder Social home page Coder Social logo

cloudnc / observable-webworker Goto Github PK

View Code? Open in Web Editor NEW
222.0 222.0 15.0 6.46 MB

Simplified API for working with Web Workers with RxJS

Home Page: https://cloudnc.github.io/observable-webworker

License: MIT License

JavaScript 6.13% TypeScript 88.32% HTML 4.18% Shell 0.49% SCSS 0.88%

observable-webworker's People

Contributors

dependabot[bot] avatar maxime1992 avatar phenomnomnominal avatar zakhenry avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

observable-webworker's Issues

Add helper operator `concurrentConcatAll()` to allow for ordered output

Currently if you pass concatAll() to the fromWorkerPool options, you will get the expected output but not the expected performance, as concatAll() does not subscribe to the next outer observable until the current inner one has completed.

There is no operator that subscribes to all outer operators asap, but buffers the emissions from inner observables that are further back in the queue.

[Question]: Is there a limitation to referenced interfaces / imports?

Hello, I have done my first walk with 'observable-webworker' and I am really excited. Everything works as it should. However, I noticed something while using it regarding references.

My project uses ngrx and so depending on the application layer within my project. I have divided
different modules with their own substores. Each of these stores contains interfaces that are used to describe the store among other things.

However, the worker is called from a service folder within the main application.

app
|---Module 1
| |----Store M1 (with Interfaces)
|
|---Module 2
| |----Store M2 (with Interfaces)
|
|---Services
| |----Service 1
| |----ServiceWorker 1
| |----Worker 1

When linking from Worker 1 to one of the interfaces, for example from module M1, errors occur during compilation (interface is not resolved correctly by Angular). But the rest of the application has no problems to use these interfaces via an import.

Currently the solution would be to extract the required interfaces and move them e.g. into a model folder under app/modules.

Is it possible to configure this and is DI through the constructor prohibited as soon as DoWork is used? I could imagine that this is a limitation of the webworkers itself.

Thanks a lot for your support.

Edit:
Here the error messages which i get as soon as i use DI through the constructor in a worker file.

Error: node_modules/@angular/core/core.d.ts:1886:13 - error TS2304: Cannot find name 'Node'.
1886     native: Node;
                 ~~~~

Error: node_modules/@angular/core/core.d.ts:7450:33 - error TS2304: Cannot find name 'Node'.
7450     findTestabilityInTree(elem: Node, findInAncestors?: boolean): Testability | null;
                                     ~~~~

Error: node_modules/@angular/core/core.d.ts:9057:28 - error TS2304: Cannot find name 'Node'.
9057         projectableNodes?: Node[][];
                                ~~~~

Error: node_modules/@angular/core/core.d.ts:9841:46 - error TS2304: Cannot find name 'Node'.
9841 export declare function ɵgetDirectives(node: Node): {}[];
                                                  ~~~~

Error: node_modules/@angular/core/core.d.ts:9854:68 - error TS2304: Cannot find name 'Element'.
9854 export declare function ɵgetHostElement(componentOrDirective: {}): Element;
                                                                        ~~~~~~~

Error: node_modules/@angular/core/core.d.ts:10280:83 - error TS2304: Cannot find name 'HTMLElement'.
10280     queuePlayer(player: ɵPlayer, context: ComponentInstance | DirectiveInstance | HTMLElement): void;
                                                                                        ~~~~~~~~~~~

Error: node_modules/@angular/core/core.d.ts:10628:48 - error90m TS2304: Cannot find name 'Document'.
10628 export declare function ɵsetDocument(document: Document | undefined): void;
                                                     ~~~~~~~~

Error: node_modules/@angular/core/core.d.ts:13426:20 - error TS2304: Cannot find name 'Document'.
13426     ownerDocument: Document;
                         ~~~~~~~~

Error: node_modules/@angular/core/core.d.ts:13427:5 - error TS2304: Cannot find name 'HTMLElement'.
13427 }): HTMLElement;
          ~~~~~~~~~~~

Error: node_modules/@angular/core/core.d.ts:13434:20 - error TS2304: Cannot find name 'Document'.
13434     ownerDocument: Document;
                         ~~~~~~~~

Error: node_modules/@angular/core/core.d.ts:13435:5 - error TS2304: Cannot find name 'Document'.
13435 }): Document;
          ~~~~~~~~

Error: node_modules/@angular/core/core.d.ts:13442:20 - error TS2304: Cannot find name 'Document'.
13442     ownerDocument: Document;
                         ~~~~~~~~


Error: node_modules/@angular/core/core.d.ts:13443:6 - error TS2304: Cannot find name 'Window'.
13443 }): (Window & typeof globalThis) | null;

Kind regards

Luigi

responseObserver.complete() is not called

return new Observable((responseObserver: Observer<Notification<Output>>) => {

First, thanks for this useful library. When using it for a single web worker, I noticed that my web worker never completes and I had to insert a call to take(1) into its pipeline. Looking at your source code, I believe the reason is that responseObserver.complete() is never called in the fromWorker function - see link.

For the full picture:

Expectation: If I use fromWorker and give it an observable which completes after emitting N events as input and use a one-to-one transformation (e.g. the identity function), then the output observable should complete after emitting N events, too.

Actual behavior: The output observable never completes.

Workaround: Insert take(N) into the pipeline on the worker side.

Angular usage: Broken clean-up when production built?

Hi, I apologize in beforehand for being a bit vague. If possible, I'll attempt to create a clear repro case but I can't right now.

We have a fairly large Angular 8 application. We're using observable-webworker for a couple of web workers, for sorting and filtering.

Everything works great in local development mode (ng serve). When built with ng build --prod however, strange things happens. It's as if the Web Workers don't do any work anymore.

One thing I noticed is they don't seem to clean up themselves the same way in dev/prod.

This is me sorting and querying in development mode:

Kapture 2019-07-31 at 16 47 29

This is me doing the exact same thing on a production build:

Kapture 2019-07-31 at 16 48 11

Does this difference tell you anything?

Typescript error when importing from 'observable-webworker'

I've got an app where I've generated a webworker using angular cli and from one of the component I wanted to use fromWorkerPool but as soon as I've got the following line:

import { fromWorkerPool } from 'observable-webworker';

The app throws errors while serving/building it:

ERROR in node_modules/rxjs/src/internal/Observable.ts(25,3): error TS2564: Property 'source' has no initializer and is not definitely assigned in the constructor.
node_modules/rxjs/src/internal/Observable.ts(28,3): error TS2564: Property 'operator' has no initializer and is not definitely assigned in the constructor.
node_modules/rxjs/src/internal/Observable.ts(75,3): error TS2394: This overload signature is not compatible with its implementation signature.
node_modules/rxjs/src/internal/Subject.ts(70,22): error TS2345: Argument of type 'T | undefined' is not assignable to parameter of type 'T'.
  Type 'undefined' is not assignable to type 'T'.
node_modules/rxjs/src/internal/Subject.ts(108,5): error TS2322: Type 'null' is not assignable to type 'Observer<T>[]'.
node_modules/rxjs/src/internal/Subject.ts(155,5): error TS2322: Type 'Observable<T> | undefined' is not assignable to type 'Observable<any>'.
  Type 'undefined' is not assignable to type 'Observable<any>'.
node_modules/rxjs/src/internal/Subject.ts(168,7): error TS2532: Object is possibly 'undefined'.
node_modules/rxjs/src/internal/Subject.ts(175,7): error TS2532: Object is possibly 'undefined'.
node_modules/rxjs/src/internal/SubjectSubscription.ts(27,5): error TS2322: Type 'null' is not assignable to type 'Subject<T>'.
node_modules/rxjs/src/internal/Subscriber.ts(99,18): error TS2345: Argument of type 'T | undefined' is not assignable to parameter of type 'T'.
  Type 'undefined' is not assignable to type 'T'.
node_modules/rxjs/src/internal/Subscriber.ts(139,5): error TS2722: Cannot invoke an object which is possibly 'undefined'.
node_modules/rxjs/src/internal/Subscriber.ts(143,5): error TS2722: Cannot invoke an object which is possibly 'undefined'.
node_modules/rxjs/src/internal/Subscriber.ts(148,5): error TS2722: Cannot invoke an object which is possibly 'undefined'.
node_modules/rxjs/src/internal/Subscriber.ts(155,5): error TS2322: Type 'null' is not assignable to type 'Subscription'.
node_modules/rxjs/src/internal/Subscriber.ts(156,5): error TS2322: Type 'null' is not assignable to type 'Subscription[]'.
node_modules/rxjs/src/internal/Subscriber.ts(187,7): error TS2322: Type '((value: T) => void) | ((value: T) => void) | ((value: T) => void) | undefined' is not assignable to type '(value: T) => void'.
  Type 'undefined' is not assignable to type '(value: T) => void'.
node_modules/rxjs/src/internal/Subscriber.ts(200,18): error TS2454: Variable 'next' is used before being assigned.
node_modules/rxjs/src/internal/Subscriber.ts(201,5): error TS2322: Type '((e?: any) => void) | undefined' is not assignable to type '(err: any) => void'.
  Type 'undefined' is not assignable to type '(err: any) => void'.
node_modules/rxjs/src/internal/Subscriber.ts(202,5): error TS2322: Type '(() => void) | undefined' is not assignable to type '() => void'.
  Type 'undefined' is not assignable to type '() => void'.
node_modules/rxjs/src/internal/Subscriber.ts(301,5): error TS2322: Type 'null' is not assignable to type 'Subscriber<T>'.
node_modules/rxjs/src/internal/Subscription.ts(33,13): error TS2322: Type 'null' is not assignable to type 'Subscription'.
node_modules/rxjs/src/internal/Subscription.ts(35,13): error TS2322: Type 'null' is not assignable to type 'Subscription[]'.
node_modules/rxjs/src/internal/Subscription.ts(37,11): error TS2322: Type 'null' is not assignable to type 'SubscriptionLike[]'.
node_modules/rxjs/src/internal/Subscription.ts(66,5): error TS2322: Type 'null' is not assignable to type 'Subscription'.
node_modules/rxjs/src/internal/Subscription.ts(67,5): error TS2322: Type 'null' is not assignable to type 'Subscription[]'.

tsconfig.worker.json:

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/worker",
    "lib": ["es2018", "webworker"],
    "types": []
  },
  "include": ["src/**/*.worker.ts"]
}

I've also tried to set skipLibCheck to true and strict to false... but no luck either.

Unfortunately cannot share the code yet and I don't have time rn to create a proper repro.

If it's not just me, then I guess it's possible to reproduce by:

  • creating a new project with angular cli
  • generate 1 webworker (that does nothing)
  • simply import import { fromWorkerPool } from 'observable-webworker'; from app.component to see what happens
  • try to ng serve or build

Upgrading to v6.0.1 and terminateOnComplete set to false is being ignored

I just updated to v6.0.1 and our web-worker is completing and being destroyed. With v6.0.0 and earlier, we were able to keep the thread alive, which is our desired workflow.

I noticed that some bug fixes went into the latest release to close the web-worker observable, but i'm wondering if something was either missed so that the terminateOnComplete option is no longer being checked, or if we were "lucky" that things were working as we liked before?

[Question]: Is it possible to use this library in an Angular library?

Hi there,

Using web workers in a Angular library doesn't seem to be supported by the Angular team at the moment.

I had a look at this GitHub issue and there are a couple of suggestions, one of which is quite involved, but looks to be a short-term solution whilst the Angular team (hopefully) work on something built-in.

However, the solution described above involves splitting apart the instantiation of the worker and the implementation detail, whereas the observable-webworker library must couple these together.

So my question is: Do you think it's possible to use this library in an Angular library? If so, how would you recommend implementing it?

I understand it's a big ask, especially considering Angular doesn't have any documentation around web workers in libraries! I shall be trying to find a solution in the mean time.

P.S. thanks a lot for this library! I struggled with trying to work with observables with the native worker but it was incredibly difficult. This library has made it a lot easier.

Angular 13: Error event is only fired

Hi iam getting actually an error by calling the lib out of my project.

and on ng serve
Warning: C:/Users/dicarm99/planning-tool/src/app/service/worker-thread/release-planning.worker.ts is part of the TypeScript compilation but it's unused. Add only entry points to the 'files' or 'include' properties in your tsconfig.

Actually i cant resolve where the problems is. Is angular 13 supported?

### Here my steps:

My setup (based on the todos and readme's):

Component

Implementing the service called by a button press:

Service

My service and the worker are located in the same directory:

My Worker

The command for initializing the env with
ng g web-worker /service/worker-thread/releasePlanning

added to angular.json:
"webWorkerTsConfig": "tsconfig.worker.json"

and the tsconfig.worker.json:
{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/worker", "lib": [ "es2018", "webworker" ], "types": [] }, "include": [ "src/**/*.worker.ts" ] }

System details:

System Info

  • OS: Windows 10
  • Node Version: v16.13.2
  • Frameworks: Angular 13.2.0
  • rxjs: 7.5.2

Types of property 'schedule' are incompatible

This is an awesome project and is making my life a lot easier. Thanks for putting it together.

I'm getting this issue when I try to use fromWorker in a project using Nx:

Types of property 'schedule' are incompatible.
    Type '<T>(work: (this: import("/Users/{ omitted }/node_modules/rxjs/src/internal/types").SchedulerAction<T>, state?: T) => void, delay?: number, state?: T) => import("/Users/{ omitted }/node_modules/rxjs/src/internal/Subscription").Subscription' is not assignable to type '<T>(work: (this: import("/Users/{ omitted }/node_modules/rxjs/internal/types").SchedulerAction<T>, state?: T) => void, delay?: number, state?: T) => import("/Users/{ omitted }/node_modules/rxjs/internal/Subscription").Subscription'.
      Types of parameters 'work' and 'work' are incompatible.
        The 'this' types of each signature are incompatible.
          Type 'import("/Users/{ omitted }/node_modules/rxjs/src/internal/types").SchedulerAction<T>' is not assignable to type 'import("/Users/{ omitted }/node_modules/rxjs/internal/types").SchedulerAction<T>'.
            Types of property 'schedule' are incompatible.
              Type '(state?: T, delay?: number) => import("/Users/{ omitted }/node_modules/rxjs/src/internal/Subscription").Subscription' is not assignable to type '(state?: T, delay?: number) => import("/Users/{ omitted }/node_modules/rxjs/internal/Subscription").Subscription'.
                Type 'import("/Users/{ omitted }/node_modules/rxjs/src/internal/Subscription").Subscription' is not assignable to type 'import("/Users/{ omitted }/node_modules/rxjs/internal/Subscription").Subscription'.
                  Property '_parentOrParents' is protected but type 'Subscription' is not a class derived from 'Subscription'.

After some googling and testing, it seems like the issue is the same as this issue in the rxjs repo. In run-worker.ts, you have:

import { NotificationKind } from 'rxjs/internal/Notification';

which is apparently what is throwing the error. I copied the code over to my project and replaced that import with this enum (which is what was being imported from the rxjs library):

export enum NotificationKind {
  NEXT = 'N',
  ERROR = 'E',
  COMPLETE = 'C'
}

After that, it works perfectly. I can open a pull request and make the change myself if you want. Or, it's just replacing that one import that fixed my particular issue if you want to make the change.

Keep up the good work!

Non-worker pool example should complete.

Example working however when I change to console out when completing nothing happens.

const input$ = of('Hello from main thread')
  fromWorker<string, string>(
    () => new Worker('./hello.worker', { type: 'module' }),
    input$,
  ).subscribe(
    message => {
      console.log(message) // Outputs 'Hello from webworker'
    },
    console.error,
    () => {
      console.log(`Hello Worker done`)
    },
  )

It's only when I add a take(1) to the worker's pipe that it actually completes.

@ObservableWorker()
export class HelloWorker implements DoWork<string, string> {
  public work(input$: Observable<string>): Observable<string> {
    return input$.pipe(
      map(message => {
        console.log(message) // outputs 'Hello from main thread'
        return `Hello from webworker`
      }),
      take(1),
    )
  }
}

This seems incorrect as of send a complete right after the next as shown here. Hopefully I'm just missing something in how to use properly.

Failed to parse source map: "ng:/observable-webworker/lib/from-worker.ts" URL is not supported

Hi,
I am using angular v10.
After upgraded from angular9 to v10 getting warning on console with --prod build

"observable-webworker": "^3.2.4"

Warning:
WARNING in ./node_modules/observable-webworker/__ivy_ngcc__/fesm5/observable-webworker.js Module Warning (from ./node_modules/source-map-loader/dist/cjs.js): Failed to parse source map: "ng:/observable-webworker/lib/from-worker-pool.ts" URL is not supported

Is there anything affect with Ivy compiler?

Broken in Dev & Canary Chrome Builds

Please be advised: https://bugs.chromium.org/p/chromium/issues/detail?id=1078821

Error: Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost/default-node_modules_observable-webworker_fesm2015_observable-webworker_mjs.js' failed to load.

The above bug WILL break this package (and any use of Worker in production WebPack apps) if it is not fixed before affected Chrome Dev & Canary builds get to the production / stable branch. It does not appear to be a bug in the observable-webworker package at this time. I do not know if there are any workarounds.

I noticed this broke because I run Canary WebView on my mobile phone. Just trying to call attention to this so that anyone here who depends on Workers actually working will be able to maybe bring some more priority to the issue over at Chromium. Please add any feedback you have to that issue.

As a quick summary, this bug affects Workers that call importScripts() and are loaded from localhost or constructed from a data/Blob URL.

Please help out and star / vote for this issue in the Chromium bug tracker. Thank you! And for anyone else who comes here looking for why Workers are broken, this is why.

Running Karma tests does not executes our webworker

When running karma unit-tests for a service or component which includes fromWorker( () => PATH) flow. The worker never get called. Is there any additional setup needed to get this run?

We are using Angular 13.

It looks like runWorker() <-- is never get called, which is defined in the worker file like your webpack 5 sample shows.

Angular production builds breaks the web worker

(Re-describing #13 in a reproducible manner)

Repro repo with code and clear description of the problem: https://github.com/monocl-oskar/observable-webworker-problem

When web workers created with observable-webworker gets run through Angular's production build mangling, they get destroyed.

For instance, this:

import { DoWork, ObservableWorker } from 'observable-webworker';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@ObservableWorker()
class HelloWorker implements DoWork<string, string> {
  public work(input$: Observable<string>): Observable<string> {
    return input$.pipe(
      map(message => {
        return 'Hello from observable webworker';
      }),
    );
  }
}

Gets mangled into this (ran through a beautifier):

! function(e) {
    var t = {};

    function r(n) {
        if (t[n]) return t[n].exports;
        var o = t[n] = {
            i: n,
            l: !1,
            exports: {}
        };
        return e[n].call(o.exports, o, o.exports, r), o.l = !0, o.exports
    }
    r.m = e, r.c = t, r.d = function(e, t, n) {
        r.o(e, t) || Object.defineProperty(e, t, {
            enumerable: !0,
            get: n
        })
    }, r.r = function(e) {
        "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, {
            value: "Module"
        }), Object.defineProperty(e, "__esModule", {
            value: !0
        })
    }, r.t = function(e, t) {
        if (1 & t && (e = r(e)), 8 & t) return e;
        if (4 & t && "object" == typeof e && e && e.__esModule) return e;
        var n = Object.create(null);
        if (r.r(n), Object.defineProperty(n, "default", {
                enumerable: !0,
                value: e
            }), 2 & t && "string" != typeof e)
            for (var o in e) r.d(n, o, (function(t) {
                return e[t]
            }).bind(null, o));
        return n
    }, r.n = function(e) {
        var t = e && e.__esModule ? function() {
            return e.default
        } : function() {
            return e
        };
        return r.d(t, "a", t), t
    }, r.o = function(e, t) {
        return Object.prototype.hasOwnProperty.call(e, t)
    }, r.p = "", r(r.s = "zAnl")
}({
    zAnl: function(e, t, r) {
        "use strict";
        r.r(t), Error, "function" == typeof Symbol && Symbol
    }
});

No trace of 'Hello from observable webworker' or even addEventListener for the web worker.

How to debug Observable Worker Class in DevTools

Hello,

i can't access inside Observable Worker Class when debugging in devtools, just have

module.exports = __webpack_public_path__ + "0.worker.js"

Without observable-webworker, i have no problem

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Not compatible with Angular 12 & Webpack 5 --prod build (required update)

Hello, first, thanks for this awesome library!

Angular 12 is forcing an upgrade to Webpack 5 (it is no longer optional), and this package does not seem to be compatible with the latest update -- upgrading has resulted in 100% reproducibly broken web-workers --- https://github.com/angular/angular-cli/releases/tag/v12.0.0-next.9 (angular cli release notes regarding Webpack forced upgrade)

I have created a minimal reproduction that demonstrates the various issues I have not been able to solve. I've tried various attempts at getting the syntax working, but so far nothing has.

Depending on the syntax used, fromWorker either silently fails entirely, or throws strange errors attempting to communicate with its workers.

Any thoughts about this? I can't seem to find a good reason why this doesn't work, and the error messages are super vague (or at least I am not familiar enough to understand them).

Reproduction steps:

git clone [email protected]:lincolnthree/example-webworker-broken-angular.git
git checkout observable-webworker
npm i
ng serve --prod
# open localhost:4200
# open dev tools and observe failures

App code:


    const input$ = new Subject<string>();

    /*
     * 1. This syntax results in code that never seems to be called/never resolves.
     */
    const getWorkerFailsSilently = () => new Worker(new URL('./app.worker', import.meta.url), { type: 'module' });
    fromWorker(getWorkerFailsSilently, input$, null, {
      terminateOnComplete: true
    })
      .subscribe({
        complete: () => console.log('1. getWorkerFailsSilently COMPLETE'),
        error: error => console.error('1. getWorkerFailsSilently', error),
        next: msg => console.warn('1. getWorkerFailsSilently', msg)
      });


    /*
     * 2. This syntax results in code that gets called but results in an error.
     */
    const getWorkerFailsWithError = () => {
      const url = new URL('./app.worker', import.meta.url);
      const worker = new Worker(url, { type: 'module' });
      return worker;
    };
    fromWorker(getWorkerFailsWithError, input$, null, {
      terminateOnComplete: true
    })
      .subscribe({
        complete: () => console.log('2. getWorkerFailsWithError COMPLETE'),
        error: error => console.error('2. getWorkerFailsWithError', error),
        next: msg => console.warn('2. getWorkerFailsWithError', msg)
      });

    /*
     * 3. This syntax results in code that gets called but results in an error (expected since it's not using 'type: "module"').
     */
    const getWorkerFailsWithErrorNoModule = () => {
      const url = new URL('./app.worker', import.meta.url);
      const worker = new Worker(url);
      return worker;
    };
    fromWorker(getWorkerFailsWithErrorNoModule, input$, null, {
      terminateOnComplete: true
    })
      .subscribe({
        complete: () => console.log('3. getWorkerFailsWithErrorNoModule COMPLETE'),
        error: error => console.error('3. getWorkerFailsWithErrorNoModule', error),
        next: msg => console.warn('3. getWorkerFailsWithErrorNoModule', msg)
      });

    input$.next('Hello world!');

Worker code:

/// <reference lib="webworker" />

import { DoWork, ObservableWorker } from 'observable-webworker';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@ObservableWorker()
export class ExampleWorker implements DoWork<string, string> {

  constructor() {
    console.warn('Created worker');
  }

  public work(input$: Observable<string>): Observable<string> {
    return input$.pipe(
      switchMap(input => {
        console.warn('Worker received message:', input)
        return of('message from worker: ' + input);
      })
    );
  }

}

Messages in console:

Angular is running in development mode. Call enableProdMode() to enable production mode.
16:56:12.386 localhost/:1 Refused to execute script from 'http://localhost:4200/dca7a459b5ae24595be1.ts' because its MIME type ('video/mp2t') is not executable.
16:56:12.386 app.component.ts:61 3. getWorkerFailsWithErrorNoModule Event {isTrusted: true, type: "error", target: Worker, currentTarget: Worker, eventPhase: 2, …}
error @ app.component.ts:61
__tryOrUnsub @ Subscriber.js:183
error @ Subscriber.js:135
_error @ Subscriber.js:75
error @ Subscriber.js:55
_error @ Subscriber.js:75
error @ Subscriber.js:55
_error @ Subscriber.js:75
error @ Subscriber.js:55
worker.onerror @ observable-webworker.js:50
wrapFn @ zone.js:803
ZoneDelegate.invokeTask @ zone.js:434
onInvokeTask @ core.js:28619
ZoneDelegate.invokeTask @ zone.js:433
Zone.runTask @ zone.js:205
ZoneTask.invokeTask @ zone.js:516
invokeTask @ zone.js:1656
globalZoneAwareCallback @ zone.js:1682
error (async)
customScheduleGlobal @ zone.js:1808
ZoneDelegate.scheduleTask @ zone.js:421
onScheduleTask @ zone.js:311
ZoneDelegate.scheduleTask @ zone.js:414
Zone.scheduleTask @ zone.js:248
Zone.scheduleEventTask @ zone.js:274
(anonymous) @ zone.js:1965
desc.set @ zone.js:864
rxjs__WEBPACK_IMPORTED_MODULE_8__.Observable.pipe.kind.kind @ observable-webworker.js:50
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ map.js:16
subscribe @ Observable.js:23
call @ dematerialize.js:9
subscribe @ Observable.js:23
AppComponent @ app.component.ts:59
AppComponent_Factory @ app.component.ts:66
getNodeInjectable @ core.js:3549
instantiateRootComponent @ core.js:10102
createRootComponent @ core.js:12463
create @ core.js:25102
bootstrap @ core.js:29573
(anonymous) @ core.js:29286
_moduleDoBootstrap @ core.js:29286
(anonymous) @ core.js:29256
ZoneDelegate.invoke @ zone.js:400
onInvoke @ core.js:28632
ZoneDelegate.invoke @ zone.js:399
Zone.run @ zone.js:160
(anonymous) @ zone.js:1318
ZoneDelegate.invokeTask @ zone.js:434
onInvokeTask @ core.js:28619
ZoneDelegate.invokeTask @ zone.js:433
Zone.runTask @ zone.js:205
drainMicroTaskQueue @ zone.js:620
Promise.then (async)
scheduleMicroTask @ zone.js:603
ZoneDelegate.scheduleTask @ zone.js:424
Zone.scheduleTask @ zone.js:248
Zone.scheduleMicroTask @ zone.js:268
scheduleResolveOrReject @ zone.js:1308
ZoneAwarePromise.then @ zone.js:1466
bootstrapModule @ core.js:29281
4431 @ main.ts:11
__webpack_require__ @ bootstrap:19
__webpack_exec__ @ main.js:597
(anonymous) @ main.js:598
__webpack_require__.O @ chunk loaded:23
(anonymous) @ main.js:599
webpackJsonpCallback @ jsonp chunk loading:33
(anonymous) @ main.js:1
Show 23 more frames
16:56:12.399 index.js:52 [WDS] Live Reloading enabled.
16:56:12.405 dca7a459b5ae24595be1.ts:1 Failed to load module script: The server responded with a non-JavaScript MIME type of "video/mp2t". Strict MIME type checking is enforced for module scripts per HTML spec.
16:56:12.405 app.component.ts:44 2. getWorkerFailsWithError Event {isTrusted: true, type: "error", target: Worker, currentTarget: Worker, eventPhase: 2, …}
error @ app.component.ts:44
__tryOrUnsub @ Subscriber.js:183
error @ Subscriber.js:135
_error @ Subscriber.js:75
error @ Subscriber.js:55
_error @ Subscriber.js:75
error @ Subscriber.js:55
_error @ Subscriber.js:75
error @ Subscriber.js:55
worker.onerror @ observable-webworker.js:50
wrapFn @ zone.js:803
ZoneDelegate.invokeTask @ zone.js:434
onInvokeTask @ core.js:28619
ZoneDelegate.invokeTask @ zone.js:433
Zone.runTask @ zone.js:205
ZoneTask.invokeTask @ zone.js:516
invokeTask @ zone.js:1656
globalZoneAwareCallback @ zone.js:1682
error (async)
customScheduleGlobal @ zone.js:1808
ZoneDelegate.scheduleTask @ zone.js:421
onScheduleTask @ zone.js:311
ZoneDelegate.scheduleTask @ zone.js:414
Zone.scheduleTask @ zone.js:248
Zone.scheduleEventTask @ zone.js:274
(anonymous) @ zone.js:1965
desc.set @ zone.js:864
rxjs__WEBPACK_IMPORTED_MODULE_8__.Observable.pipe.kind.kind @ observable-webworker.js:50
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ map.js:16
subscribe @ Observable.js:23
call @ dematerialize.js:9
subscribe @ Observable.js:23
AppComponent @ app.component.ts:42
AppComponent_Factory @ app.component.ts:66
getNodeInjectable @ core.js:3549
instantiateRootComponent @ core.js:10102
createRootComponent @ core.js:12463
create @ core.js:25102
bootstrap @ core.js:29573
(anonymous) @ core.js:29286
_moduleDoBootstrap @ core.js:29286
(anonymous) @ core.js:29256
ZoneDelegate.invoke @ zone.js:400
onInvoke @ core.js:28632
ZoneDelegate.invoke @ zone.js:399
Zone.run @ zone.js:160
(anonymous) @ zone.js:1318
ZoneDelegate.invokeTask @ zone.js:434
onInvokeTask @ core.js:28619
ZoneDelegate.invokeTask @ zone.js:433
Zone.runTask @ zone.js:205
drainMicroTaskQueue @ zone.js:620
Promise.then (async)
scheduleMicroTask @ zone.js:603
ZoneDelegate.scheduleTask @ zone.js:424
Zone.scheduleTask @ zone.js:248
Zone.scheduleMicroTask @ zone.js:268
scheduleResolveOrReject @ zone.js:1308
ZoneAwarePromise.then @ zone.js:1466
bootstrapModule @ core.js:29281
4431 @ main.ts:11
__webpack_require__ @ bootstrap:19
__webpack_exec__ @ main.js:597
(anonymous) @ main.js:598
__webpack_require__.O @ chunk loaded:23
(anonymous) @ main.js:599
webpackJsonpCallback @ jsonp chunk loading:33
(anonymous) @ main.js:1
Show 23 more frames

Versions:

sharktop:example-web-worker lincoln$ ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/
    

Angular CLI: 12.0.0-next.9
Node: 14.15.0
OS: darwin x64

Angular: 12.0.0-next.9
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1200.0-next.9
@angular-devkit/build-angular   12.0.0-next.9
@angular-devkit/core            12.0.0-next.9
@angular-devkit/schematics      12.0.0-next.9
@angular/cdk                    12.0.0-next.7
@schematics/angular             12.0.0-next.9
rxjs                            6.6.7
typescript                      4.2.4

Failed to execute 'postMessage' on 'Worker': function createTask() { [native code] } could not be cloned.

Seeing this error. How do I debug this?

Failed to execute 'postMessage' on 'Worker': function createTask() { [native code] } could not be cloned.

Code:

 const input$: Observable<WatchedObservablesProperties> = of({
      tableDataSourceProvider: {
        data: this.tableDataSourceProvider.data,
      },
      columnConfigProvider: {
        columnConfigs$: this.columnConfigProvider.columnConfigs$
      },
      columnStateChangeProvider: {
        columnState$: this.columnStateChangeProvider.columnState$
      },
      rowStateChangeProvider: {
        rowState$: this.rowStateChangeProvider.rowState$,
        mode: this.rowStateChangeProvider.mode,
        selectionMode: this.rowStateChangeProvider.selectionMode,
        initialExpandAll: this.rowStateChangeProvider.initialExpandAll
      },
      filtersProvider: {
        filters$: this.filtersProvider.filters$,
        queryProperties$: this.filtersProvider.queryProperties$
      },
      paginationProvider:this.paginationProvider ? {
        pageEvent$: this.paginationProvider.pageEvent$,
        pageIndex: this.paginationProvider.pageIndex,
        pageSize: this.paginationProvider.pageSize,
        totalItems: this.paginationProvider.totalItems
      }: undefined,
      loadingStateSubject$: this.loadingStateSubject,
    });

    fromWorker<WatchedObservablesProperties, StatefulTableRow[]>(
      () => new Worker(new URL('./table-cdk.worker', import.meta.url), { type: 'module', name: 'md5-worker' }),
      input$,
    ).subscribe({
      next: (data) => this.rowsChange$.next(data),
      error: (error)=> this.rowsChange$.error(error)
    });

Ang11 + Webpack 5.... Module parse failed: ParserHelpers.addParsedVariableToModule is not a function

Hello all,
I feel very alone with this problem... Am I the only one that tried to migrate to Angular 11 and cannot 'compile' anymore their worker...
I can't belive it.
I use : return fromWorker(() => new Worker('./myWorker.worker.ts',{type: 'module'}), input$
And it does not want to compile (Module parse failed: ParserHelpers.addParsedVariableToModule is not a function)

I read that the new syntax need a 'new URL(....' (GoogleChromeLabs/worker-plugin#88)
Compile, but the worker is not called properly from browser...

Help would be appreciated, I am on the 3thrd google page which is not a good sign... :/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.