패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.1.1

isolated_worker

Flutter(Isolate) 및 Web(Web Worker)용 싱글턴 고립 워커입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
6.4천
좋아요
89
Pub 점수
130

패키지 설치

flutter pub add isolated_worker

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

isolated_worker 는 Flutter 및 웹 플랫폼용 싱글톤 워커 구현을 제공하며, 모바일에서는 Isolates 를, 웹에서는 Web Workers 를 활용합니다. 무거운 작업을 메인 스레드에서 분리하여 효율적인 백그라운드 처리를 가능하게 하여 앱의 반응성을 향상시킵니다. 이 패키지는 플랫폼별 차이점을 추상화하여 Android, iOS, Web, macOS, Windows, Linux 에서 일관된 API 를 제공하여 격리된 실행을 관리할 수 있게 합니다. 데이터 파싱, 이미지 처리, 긴 실행 시간의 계산과 같은 CPU 집약적 작업에 적합합니다.

사용 사례

  • 백그라운드 데이터 처리
  • 이미지 또는 파일 조작
  • 장시간 실행 계산
  • 실시간 데이터 분석
  • 크로스 플랫폼 백그라운드 작업

주요 기능

  • 싱글턴 워커 패턴
  • 모든 플랫폼용 통합 API
  • 자동 플랫폼 감지
  • 메시지 전달 지원
  • 내장된 오류 처리

적합한 대상

  • 크로스 플랫폼 백그라운드 실행이 필요한 개발자
  • CPU 집약적 작업을 수행하는 앱
  • 다양한 플랫폼 간 코드 재사용을 우선시하는 팀
  • 집중적인 작업 중에 반응형 UI가 필요한 프로젝트
  • 다양한 운영 체제를 대상으로 하는 Flutter 앱

고려 사항

  • 이소레이트 통신에 대한 이해가 필요합니다
  • 하나의 활성 워커 인스턴스로 제한
  • 메시지 직렬화 오버헤드
  • 적절한 설계 없이 입출력 중심 작업에 적합하지 않음
  • 플랫폼별 제한 사항이 적용될 수 있습니다

원본 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 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.