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

패키지 상세v1.0.2

isolate_handler

격리 간 통신을 지원하는 사용하기 쉬운 격리 추상화 계층.

AndroidiOS
30일 다운로드
3천
좋아요
102
Pub 점수
160

패키지 설치

flutter pub add isolate_handler

패키지 개요

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

isolate_handler는 Dart의 Isolate를 관리하기 위한 간단한 추상화 계층을 제공하여 Isolate 간 원활한 통신을 가능하게 합니다. Isolate의 생성과 조율을 단순화하여 개발자가 무거운 계산 작업을 낮은 수준의 복잡성 없이 오프로드할 수 있도록 해줍니다. 메인 스레드와 Isolate 스레드 간의 메시지 전달을 지원하며, 데이터 처리나 파일 작업과 같은 CPU 집약적인 작업에 이상적입니다. 깔끔한 API와 내장된 오류 처리 기능을 통해 Flutter 애플리케이션에서 코드의 가독성과 유지보수성을 향상시킵니다.

사용 사례

  • 백그라운드 계산
  • 파일 처리
  • 데이터 변환
  • 실시간 분석
  • 중량 작업 오프로드

주요 기능

  • 간편한 아일랏 관리
  • 내장 메시지 전달
  • 오류 처리
  • 클린한 API 설계
  • 크로스 플랫폼 지원

적합한 대상

  • 백그라운드 처리가 필요한 개발자
  • CPU 집약적 작업을 수행하는 앱
  • 코드 간결성을 우선시하는 팀
  • Android 및 iOS를 대상으로 하는 Flutter 앱

고려 사항

  • isolates 개념에 대한 이해가 필요합니다
  • Android 및 iOS 플랫폼에만 제한됨
  • 앱 크기가 약간 증가할 수 있습니다
  • 격리된 isloate에서 직접 UI 업데이트에 적합하지 않습니다

원본 README

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

Isolate Handler

Effortless isolates abstraction layer with support for inter-isolate communication. These isolates (unlike the standard ones in Flutter) can call platform plugins.

Getting Started

What's an isolate?

In the words of the Dart documentation itself, isolates are:

Independent workers that are similar to threads but don't share memory, communicating only via messages.

In short, Dart is a single-threaded language, but it has support for concurrent execution of code through isolates.

This means that you can use isolates to execute code you want to run alongside your main thread, which is particularly useful for keeping your Flutter application running smoothly.

For more detailed information, please read this excellent article by Didier Boelens.

Why should I use Isolate Handler?

Short answer: Isolate Handler allows easy spawning of—as well as communication between—isolates.

Dart already has a very clean interface for spawning and interacting with isolates, using Isolate Handler instead of the regular interface only provides a slightly simpler way of keeping track of and communicating with them. Besides, it allows the isolates to call platform plugins, overcoming a limitation of the original ones.

Plugins in Flutter parlance mean packages that contain native code. When you depend on something in your pubspec.yaml file, that might be either a package (containing Dart code only) or a plugin (containing platform code, usually Android and iOS, maybe even more).

Plugins use a mechanism called platform channel to communicate between the Dart and the native sides, a message passing mechanism using the MethodChannel type. This mechanism depends on elements of the underlying UI engine to function. Standard isolates don't have that underlying engine because it's not something they normally need but this means that any call to a plugin (eg. to something as simple as path_provider) will fail.

The FlutterIsolate type used by this package, however, does set up that mechanism (technically by creating a background view on the platform side) so that calls to plugins go through completely transparently, without any code modification at all: just call as you would normally call from your main thread code.

It is worth noting, however, that running native plugins from a Dart isolate does not offer any real performance advantage as all native code is run on the main (UI) thread by default. In simple terms, using an isolate (unlike async/await itself) will create parallel execution on a different thread. But as soon as you call a plugin from that isolate, the platform side of that plugin will run on the UI thread again. Calling a plugin from an isolate instead of the main app will not create a new thread on the native platform: only the Dart code will enjoy the benefits, not the native part.

If your tasks are computationally intensive on the Dart side, isolates will help a lot. If the time is spent in the plugin native side, you won't gain much unless you create your own native threads on the native side, in the plugin itself. There is nothing you can do about it in your main Dart app.

Using Isolate Handler

Spawning an isolate

Spawning an isolate with Isolate Handler is really simple:

IsolateHandler().spawn(entryPoint);

This is similar to how isolates are spawned normally, with the exception that Isolate Handler does not expect a message parameter, only an entry point. Messaging has been abstracted away and a communications channel is instead opened automatically.

Communicating with an isolate

Just spawning an isolate provides no benefit over simply using Isolate.spawn, so let's move on to a slightly more useful example; sending data to an isolate and receiving some back.

Let's do a complete project where we start an isolate and send it an integer, have it add one to our count and return the value. We will also give our isolate a name to make it easy to access from anywhere.

final isolates = IsolateHandler();
int counter = 0;

void main() {
  // Start the isolate at the `entryPoint` function.
  isolates.spawn<int>(entryPoint,
    name: "counter",
    // Executed every time data is received from the spawned isolate.
    onReceive: setCounter,
    // Executed once when spawned isolate is ready for communication.
    onInitialized: () => isolates.send(counter, to: "counter")
  );
}

// Set new count and display current count.
void setCounter(int count) {
  counter = count;
  print("Counter is now $counter");
  
  // We will no longer be needing the isolate, let's dispose of it.
  isolates.kill("counter");
}

// This function happens in the isolate.
// Important: `entryPoint` should be either at root level or a static function.
// Otherwise it will throw an exception.
void entryPoint(Map<String, dynamic> context) {
  // Calling initialize from the entry point with the context is
  // required if communication is desired. It returns a messenger which
  // allows listening and sending information to the main isolate.
  final messenger = HandledIsolate.initialize(context);

  // Triggered every time data is received from the main isolate.
  messenger.listen((count) {
    // Add one to the count and send the new value back to the main
    // isolate.
    messenger.send(++count);
  });
}

Breaking changes from 0.2.0

Due to a change in the Flutter framework, the previously used method to set up an extra communication channel cannot be used any more. From now on, this package depends on flutter_isolate to use an alternative method to establish the platform channel so that the isolates can call platform plugins.

This solution is mostly transparent but it results in two changes. First, as it can be seen in the code above, the parameter passed to the entryPoint() function changed type. It was a HandledIsolateContext earlier but it is a Map<String, dynamic> now. It still has the same two elements as before, 'messenger' (a SendPort) and 'name' (a String).

The second change pertains to the way external plugins are called from the isolates. There is no need for any setup now, just call the plugin just like you would call it from the main thread. See the example subproject for a sample.

카테고리

의존성

의존성 목록 1 개

소스 저장소

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