2

I am using WorkManager for Background Service. My code is as follows

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    switch (task) {
      case "uploadLocalData":
        print("this method was called from background!");
        await BackgroundProcessHandler().uploadLocalData();
        print("background Executed!");
        return true;
       
        break;
      case Workmanager.iOSBackgroundTask:
        print("iOS background fetch delegate ran");
        return true;
        break;
    }
    return false;
   
  });
}

is there any way to wait for async method in executeTask ?

1 Answers1

2

The way to asyncify non-async things is through completers. You create a completer, await on its future and complete it in the future.

Completer uploadCompleter = Completer();

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    switch (task) {
      case "uploadLocalData":
        print("this method was called from background!");
        await BackgroundProcessHandler().uploadLocalData();
        print("background Executed!");
        uploadCompleter.complete();
        return true;
       
        break;
      case Workmanager.iOSBackgroundTask:
        print("iOS background fetch delegate ran");
        return true;
        break;
    }
    return false;
   
  });
}

// somewhere else
await uploadCompleter.future;

Gazihan Alankus
  • 11,256
  • 7
  • 46
  • 57
  • just added ```await uploadCompleter.future;``` above to the ```uploadCompleter.complete();```, this worked perfectly for me. Thanks @GazihanAlankus – Raksha Deshmukh Jan 05 '21 at 06:24
  • I'm glad it helped, but I don't undersdand :) If you `await uploadCompleter.future;` before `uploadCompleter.complete();`, it will never get to `uploadCompleter.complete();`, right? – Gazihan Alankus Jan 05 '21 at 07:16
  • I'm also shocked, bcoz conceptually it's wrong,.. but it worked for me. – Raksha Deshmukh Jan 06 '21 at 04:44