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

패키지 상세v7.2.9

worker_manager

worker_manager는 고성능 계산을 Isolate 간에 관리할 수 있게 해줍니다

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
5.3만
좋아요
399
Pub 점수
145

패키지 설치

flutter pub add worker_manager

패키지 개요

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

worker_manager 패키지는 CPU 집약적인 작업을 Dart의 고립 영역에 분산시켜 효율적인 관리를 가능하게 하며 앱의 반응성과 성능을 향상시킵니다. 메인 UI 스레드를 차단하지 않고 백그라운드 계산의 생성, 실행 및 조정을 간소화합니다. 대량의 데이터 처리, 이미지 조작 또는 복잡한 계산에 적합하며, 고립 영역 간 통신 및 라이프사이클 이벤트를 다루기 위한 명확한 API를 제공합니다. 이 패키지는 크로스플랫폼으로 Android, iOS, Web, macOS, Windows, Linux를 지원합니다.

사용 사례

  • 대량 데이터 처리
  • 이미지 또는 파일 변환
  • UI 앱에서의 백그라운드 계산
  • 실시간 분석
  • 복잡한 수학 연산

주요 기능

  • Isolate 기반 동시성
  • 작업 관리를 위한 간단한 API
  • 크로스 플랫폼 지원
  • 자동 오류 처리
  • 작업 라이프사이클 모니터링

적합한 대상

  • 성능 중심 애플리케이션
  • 집중적인 백그라운드 작업을 가진 앱
  • 이소레이트 관리가 필요한 개발자
  • 반응형 UI가 필요한 플러터 앱
  • 다중 플랫폼을 대상으로 하는 프로젝트

고려 사항

  • 격리체에 대한 이해가 필요합니다
  • CPU 중심 작업에 제한됨
  • 잠재적인 메모리 오버헤드
  • 입출력 집약적인 작업에 적합하지 않습니다
  • 격리 간에 주의 깊은 상태 관리가 필요합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

Worker Manager

Worker Manager is a powerful and easy-to-use library that helps you efficiently manage CPU-intensive tasks in your Flutter applications. It offers several advantages over traditional async programming or the built-in compute method. Note that the functions you are passing should either be static methods, globally defined functions or lambdas to ensure they are accessible from other isolates.

New Feature - dynamicSpawn flag in init

By using this flag, worker_manager changes its behavior regarding isolate management. If this flag is set to true, new isolates will be spawned only if necessary and killed when they are no longer needed.

Advantages

Efficient Scheduling

This library schedules CPU-intensive functions to avoid skipping frames or freezes in your Flutter application. It ensures that your app runs smoothly, even when dealing with heavy computations.

Reusable Isolates

Unlike the compute method, which always creates a new Dart isolate, Worker Manager reuses existing isolates. This approach is more efficient and prevents overloading the CPU. When resources are not freed up, using the compute method may cause freezes and skipped frames.

Cancelable Tasks

Worker Manager provides a cancellation functionality through the Cancelable class and its cancel method. This feature allows developers to free up resources when they are no longer needed, improving the app's performance and responsiveness.

Gentle Cancellation

In addition to the standard cancellation method, Worker Manager offers a more gentle approach to cancellation. This new feature, executeGentle, does not immediately terminate the Dart isolate but instead provides a lambda function that can be called periodically within the task to check if it should be cancelled. This allows tasks to clean up and terminate gracefully.

Inter-Isolate Communication

The library supports communication between isolates with the executeWithPort method. This feature enables sending progress messages or other updates between isolates, providing more control over your tasks.

Gentle Cancellation with Port

The executeGentleWithPort method is another valuable feature of Worker Manager that combines gentle cancellation and inter-isolate communication. It accepts two arguments: a port for inter-isolate communication and a getter function isCancelled for gentle cancellation. This offers more flexibility and control, allowing tasks to communicate with other isolates while also providing an opportunity for graceful termination.

Usage

Execute the task

Cancelable<ResultType> cancelable = workerManager.execute<ResultType>(
  () async {
    // Your CPU-intensive function here
  },
  priority: WorkPriority.immediately,
);

Execute a Task with Gentle Cancellation

Cancelable<ResultType> cancelable = workerManager.executeGentle<ResultType>(
  (isCanceled) async {
    while (!isCanceled()) {
      // Your CPU-intensive function here
      // Check isCanceled() periodically to decide whether to continue or break the loop
    }
  },
  priority: WorkPriority.immediately,
);

Execute a Task with Inter-Isolate Communication

Cancelable<ResultType> cancelable = workerManager.executeWithPort<ResultType, MessageType>(
  (SendPort sendPort) async {
    // Your CPU-intensive function here
    // Use sendPort.send(message) to communicate with the main isolate
  },
  onMessage: (MessageType message) {
    // Handle the received message in the main isolate
  },
);

Execute a Task with Gentle Cancellation and Inter-Isolate Communication

Cancelable<ResultType> cancelable = workerManager.executeGentleWithPort<ResultType, MessageType>(
  (SendPort sendPort, IsCanceled isCanceled) async {
    while (!isCanceled()) {
      // Your CPU-intensive function here
      // Use sendPort.send(message) to communicate with the main isolate
      // Check isCanceled() periodically to decide whether to continue or break the loop
    }
  },
  onMessage: (MessageType message) {
    // Handle the received message in the main isolate
  },
  priority: WorkPriority.immediately,
);

Cancel a Task

cancelable.cancel();

Dispose Worker Manager

await workerManager.dispose();

Notice

Before isolates support in wasm, implementation of execution of task same as compute method from foundation

Conclusion

By using Worker Manager, you can enjoy the benefits of efficient task scheduling, reusable isolates, cancellable tasks, and inter-isolate communication. It provides a clear advantage over traditional async programming and the built-in compute method, ensuring that your Flutter applications remain performant and responsive even when handling CPU-intensive tasks. The additional executeGentleWithPort feature provides both gentle cancellation and inter-isolate communication for your tasks, offering further control and efficiency.

카테고리

의존성

의존성 목록 4 개

소스 저장소

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