Call async function from Isolate function
Asked Answered
I

1

8

I am trying to call an async function from the Isolate function.

class IsolateExample {

  final ReceivePort port = new ReceivePort();

  IsolateExample(){
     Isolate.spawn(isolateFunction, port.sendPort);
  }

  static isolateFunction(SendPort port){
    print('inside isolateFunction');
    asyncFunction();
  }

  static void asyncFunction() async {
    print('inside asyncFunction');
  }
}

Usage of above class:

final IsolateExample _isolate = new IsolateExample();

Above code looks simple but asyncFunction never gets called. I do not have any clue why this is failing.

Insole answered 14/5, 2018 at 16:19 Comment(4)
Did you have a look at docs.flutter.io/flutter/foundation/compute.html ?Agonic
I have simplified the above. In the actual code, I need to return multiple values over the time. I guess compute() does not support multiple returns.Insole
No, compute only supports a single sync return value. There is an open issue to support a single async return value.Agonic
Well, as of now, that sample has no issue. I'm able to see that print('inside asyncFunction')Cense
O
0

Isolate will only run your compute once. If you'd like to call the function inside the isolate in intervals, you can utilize Timer.periodic() similar to how it's demonstrated on this post.

Once you're done running the function inside the isolate, you can terminate it with isolate.kill() - given that isolate contains Isolate.spawn()

Omar answered 27/4, 2022 at 2:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.