rmawatson/flutter_isolate

resume function not working with async/await

Closed this issue · 4 comments

Hi
I have to try calling an async method on the isolate but after call resume method are not run await code.
This is my code:

void pauseIsolate() {
isolate.pause();
emit(ProgressPausState());
}

void resumeIsolate() {
// Completer();
isolate.resume();
updateProgress();
}

void mainIsolate() async {
final receivePort = ReceivePort();
isolate =
await FlutterIsolate.spawn(apiCalling, receivePort.sendPort);
receivePort.listen((dynamic response) async {
if (response is String) {
progress++;
updateProgress();
} else if (response is Error) {}
if(progress==10){
isolate.kill();
print("Kill Isolate");
emit(ProgressInitial());
}
});
}
@pragma('vm:entry-point')
static void apiCalling(SendPort sendPort) async {
print("Call API Four");
for(int i =0; i < 10; i++) {
final data = await http
.get(Uri.parse('https://random-data-api.com/api/v2/users?size=$i'));
final dataList = jsonDecode(data.body);
print(dataList);
sendPort.send("Add succeed");
}
}

Please provide a minimal reproducible sample project that I can clone and run.

Hello @nmfisher

my overall aim is when the application to start at that time fetch data from multiple APIs in the background of the app and store the data on the local database, because of running the app in offline mode.

https://github.com/Dev11-ultroNeous/workers/tree/development

In this repo, I have tried to call multiple APIs on the sync button of the home page.

this page links to call APIs, kindly check the commented code and actual code on this page.
I am facing the issue of no resume isolate.

https://github.com/Dev11-ultroNeous/workers/blob/development/lib/bloc/progresscubit/progress_cubit.dart

In this repo call APIs sequentially, can we call simultaneously?

Going from that code alone, you are spawning an isolate here:

https://github.com/Dev11-ultroNeous/workers/blob/ca7b23e9ba8facd5b639415d8455fed4d1dd75c0/lib/bloc/progresscubit/progress_cubit.dart#L87

then pausing FlutterIsolate.current here:

https://github.com/Dev11-ultroNeous/workers/blob/ca7b23e9ba8facd5b639415d8455fed4d1dd75c0/lib/bloc/progresscubit/progress_cubit.dart#L28

I assume you trying to pause/resume from the main isolate (i.e. main Flutter "thread"), so FlutterIsolate.current will not refer to the isolates you spawned. You need to call pause/resume on the actual isolates you created, like:

final isolate =
        await FlutterIsolate.spawn(entryPoint, receivePort.sendPort);
isolate.pause()