Dev to webs {Coding…}

ร บทเรียนฟรีด้านการพัฒนาซอฟต์แวร์ ที่ครอบคลุมเนื้อหาหลากหลาย ตั้งแต่การเขียนโค้ดพื้นฐานไปจนถึงเทคนิคขั้นสูง

บทที่ 19: การใช้ Isolate และ compute() สำหรับงาน Background

🔖 หมวดบทเรียน: การจัดการงานหนักใน background โดยไม่กระทบ UI

📌 เหมาะสำหรับ: แอปที่มีการประมวลผลหนัก เช่น โหลดไฟล์, แปลงข้อมูล, ทำ AI/ML, คำนวณซับซ้อน

🎯 เป้าหมาย: แยกงานหนักไปไว้ใน isolate เพื่อลดภาระของ main thread และ UI ไม่กระตุก

🧭 เกริ่นนำ

Flutter ทำงานบน single thread (UI thread) ถ้างานหนักรันตรง ๆ บน main thread จะทำให้ UI กระตุก Isolate คือเครื่องมือที่ Dart ให้มาเพื่อรัน code หนักใน thread แยก โดยไม่แชร์ memory แต่ใช้การส่งข้อมูลผ่าน message แทน

หากงานไม่ซับซ้อนมาก สามารถใช้ compute() เป็นวิธีง่าย ๆ สำหรับ background task

🚀 ใช้ compute() อย่างง่าย

import 'package:flutter/foundation.dart';

String heavyTask(String input) {
  // ทำงานหนัก เช่น loop, decode, ฯลฯ
  return input.toUpperCase();
}

Future<void> runTask() async {
  final result = await compute(heavyTask, 'hello');
  print(result); // "HELLO"
}

🔁 ตัวอย่าง: ประมวลผล JSON ขนาดใหญ่

Future<List<User>> parseJsonInBackground(String jsonString) async {
  return compute(parseUsers, jsonString);
}

List<User> parseUsers(String jsonString) {
  final data = jsonDecode(jsonString) as List;
  return data.map((e) => User.fromJson(e)).toList();
}

💡 ข้อควรรู้

  • compute() รับได้แค่ function ที่เป็น top-level หรือ static และรับ-ส่ง parameter ได้แค่ 1 ตัว
  • ใช้ ReceivePort และ Isolate.spawn() หากต้องการควบคุม isolate เอง

🧰 ใช้ Isolate ด้วยตนเอง (advance)

void isolateEntry(SendPort sendPort) {
  int result = 0;
  for (int i = 0; i < 100000000; i++) {
    result += i;
  }
  sendPort.send(result);
}

void startManualIsolate() async {
  final receivePort = ReceivePort();
  await Isolate.spawn(isolateEntry, receivePort.sendPort);
  receivePort.listen((data) => print("Result: \$data"));
}

✅ สรุป

  • compute() ง่าย เหมาะกับงานเบา-กลาง ที่ใช้ background thread ชั่วคราว
  • Isolate.spawn() ใช้สำหรับงานที่ต้องรันต่อเนื่องหรือควบคุมละเอียด
  • ช่วยให้ UI ไม่กระตุกขณะรันงานหนัก

บทสุดท้ายเราจะเรียนรู้เรื่อง การนำแอปขึ้น Production: signing, obfuscation, ขนาดไฟล์, release build