Skip to content

compute function different from describe? #116697

@SirLYC

Description

@SirLYC
import 'dart:isolate';

import 'package:flutter/foundation.dart';

class BackgroundPlus {
  final PlusData plusData;

  BackgroundPlus(this.plusData);

  Future<int> computeInBackground() async {
    return compute(_computeEntry, plusData);
  }

  int _computeEntry(PlusData plusData) {
    print(
        "_computeEntry isolate: ${Isolate.current.debugName}@${Isolate.current.hashCode}");
    return plusData.a + plusData.b;
  }
}

class PlusData {
  final int a;
  final int b;

  PlusData(this.a, this.b);
}

void main() async {
  print(
      "main isolate: ${Isolate.current.debugName}@${Isolate.current.hashCode}");
  final data = await BackgroundPlus(PlusData(2, 3)).computeInBackground();
  print("data=$data");
}

After I run code below, this message on console is:

image

Which means I can run compute function with memeber function and user-defined class. But the descibe of the compute function is:

  • callback:
/// {@template flutter.foundation.compute.callback}
/// Qualifying functions include:
///
///   * top-level functions
///   * static methods
///   * closures that only capture objects that can be sent to an isolate
  • message
/// There are limitations on the values that can be sent and received to and
/// from isolates. These limitations constrain the values of `Q` and `R` that
/// are possible. See the discussion at [SendPort.send].

Why this works? One possible reason I guess is that Isolate.spawn will copy all memory hold by its message param to the new isolate. After I read descibe of Isolate.spaw carefully, I didn't find any limitation on message param. So I guess the _IsolateConfiguration params passed to compute function will be copied too. Since callback is a member funtion pointer, the whole object will be deep copied too.

If my guess is correct, the describe of compute is misleading user force use limited function and message type; Or else, use member function and user defined class member will bring some harm?

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listdependency: dartDart team may need to help usengineflutter/engine related. See also e: labels.r: fixedIssue is closed as already fixed in a newer version

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions