パッケージ、リポジトリ、アプリカテゴリを検索

パッケージ詳細v0.1.1

isolated_worker

Flutter(Isolate)および Web(Web Worker)用のシングルトン隔離ワーカー。

AndroidiOSWebmacOSWindowsLinux
30日間ダウンロード
6420
いいね数
89
Pub ポイント
130

パッケージをインストール

flutter pub add isolated_worker

パッケージ概要

公開情報に基づく選定ガイドです。参考としてご利用ください。

isolated_worker は Flutter および Web プラットフォーム向けにシングルトンワーカーの実装を提供し、モバイルでは Isolates を、Web では Web Workers を活用します。重いタスクをメインスレッドから分離することで、効率的なバックグラウンド処理が可能になり、アプリの応答性が向上します。このパッケージはプラットフォーム固有の違いを抽象化し、Android、iOS、Web、macOS、Windows、Linux で一貫した API を提供して、隔離実行を管理できます。データ解析、画像処理、長時間実行される計算などの CPU 高負荷処理に最適です。

用途

  • バックグラウンドデータ処理
  • 画像またはファイルの操作
  • 長時間実行の計算
  • リアルタイムデータ分析
  • クロスプラットフォームのバックグラウンドタスク

主な機能

  • シングルトンワーカーパターン
  • すべてのプラットフォーム向けの統合 API
  • 自動プラットフォーム検出
  • メッセージ送信のサポート
  • 組み込みのエラー処理

適している対象

  • クロスプラットフォームのバックグラウンド実行が必要な開発者
  • CPU集約的な処理を行うアプリ
  • 複数プラットフォーム間でのコード再利用を重視するチーム
  • 集中的なタスク中に応答性のあるUIを必要とするプロジェクト
  • 複数のオペレーティングシステム向けの Flutter アプリ

注意事項

  • 隔離通信の理解が必要です
  • 1つのアクティブなワーカーインスタンスに制限
  • メッセージシリアル化のオーバーヘッド
  • 適切な設計がなければ、I/Oバウンドタスクには向いていません
  • プラットフォーム固有の制限が適用される場合があります

元の README

関連するソースリポジトリの README 原文のスナップショットです。最新の内容はリポジトリをご覧ください。

A singleton isolated worker for all platforms. On most platforms, it uses Flutter's Isolate, except on the web, since Isolate is not available, it uses Worker instead.

Features

  • 💙 Easy to use*
  • 👬 Identical syntax to the compute function provided by Flutter*
  • 🚫 Not a one-off worker
  • 🌐 Available on web**

*except on web **by using JsIsolatedWorker

Usage

Basic example
int doSomeHeavyCalculation(int count) {
    // ...
}
void main() {
    // if using compute function:
    // compute(doSomeHeavyCalculation, 1000);
    IsolatedWorker().run(doSomeHeavyCalculation, 1000);
}

If we want to do some heavy work that does not need any arguments and/or return values.

// WRONG
void doSomethingHeavy() {
    // ...
}

// CORRECT
void doSomethingHeavy(void _) {
    // ...
}

void main() {
    IsolatedWorker().run(doSomethingHeavy, null);
}

Web example

We can utilize the JsIsolatedWorker for spawning a web worker. However, it cannot use Dart closures as messages to the worker because of some limitations (I have tried using JSONfn and allowInterop but no luck). Instead we need to use native JS closures. In order to do this, we can utilize existing JS APIs or by importing external libraries/files.

Let's assume we want to stringify objects using JSON.stringify.

void main() {
    JsIsolatedWorker().run(
        functionName: ['JSON', 'stringify'],
        arguments: {},
        // optional argument, in case web worker is not available.
        fallback: () {
            return '{}';
        },
    ).then(print);
    // prints "{}"
}

Now let's assume we have external js libraries/files that we want the worker to use.

void main() async {
    // import the scripts first
    // and check if web worker is available
    final bool loaded = await JsIsolatedWorker().importScripts(['myModule1.js']);
    // web worker is available
    if(loaded) {
        print(await JsIsolatedWorker().run(
            functionName: 'myFunction1',
            arguments: 'Hello from Dart :)',
        ));
    }else{
        print('Web worker is not available :(');
    }
}

Shared Platform Worker

There might be a case where we need to use both IsolatedWorker and JsIsolatedWorker. There are many ways to go about it. We can use conditional import, dependency injections, or WorkerDelegator.

WorkerDelegator

For example, we have a foo Dart method that returns a list of numbers from 1 to count.

List<int> foo(int count) {
    List<int> result = <int>[];
    for(int i = 1; i <= count; i++) {
        result.add(i);
    }
    return result;
}

And a JS file foo.js containing a foo JS method that does the same thing.

function foo(count) {
    let result = [];
    for(let i = 1; i <= count; i++) {
        result.push(i);
    }
    return result;
}

To call these methods using WorkerDelegator, we need to create a DefaultDelegate, JsDelegate, and WorkerDelegate first. Then register the WorkerDelegate to our WorkerDelegator.

Future<void> main() async {
    const DefaultDelegate<int, List<int>> fooDelegate = 
        DefaultDelegate(callback: foo);
    
    const JsDelegate fooJsDelegate = JsDelegate(callback: 'foo');

    const WorkerDelegate<int, List<int>> workerDelegate = 
        WorkerDelegate(
            key: 'foo',
            defaultDelegate: fooDelegate,
            jsDelegate: fooJsDelegate,
        );
    
    WorkerDelegator().addDelegate(workerDelegate);

    // Don't forget to call importScripts for our "foo" js method.
    await WorkerDelegator().importScripts(const <String>['foo.js']);
}

After registering our WorkerDelegate, we just need to call it using its key "foo".

...
print(await WorkerDelegator().run('foo', 9));
...

The key can be anything except null.

enum DelegateKeys { foo, bar }
const WorkerDelegate<int, List<int>> workerDelegate = 
    WorkerDelegate(
        key: DelegateKeys.foo,
        defaultDelegate: fooDelegate,
        jsDelegate: fooJsDelegate,
    );

Notes: WorkerDelegator() is a singleton. If we need to create a new instance, we can create one using

WorkerDelegator.asNewInstance(
    delegates: /* pass our WorkerDelegates here. OPTIONAL. */
);

Web Worker Setup

In order for JsIsolatedWorker to run properly on Flutter web, there needs to be a single worker.js file in the web folder. You can download it here and put it in your web folder like below

...
web /
    index.html
    worker.js
    ...

Examples

  • Fetch - an example of how to get response from a URL using IsolatedWorker and JsIsolatedWorker

カテゴリー

依存関係

依存関係一覧 1 件

ソースリポジトリ

このパッケージを使用しているプロジェクト

データはまだありません。