Raksha Deshmukh
Raksha Deshmukh

Reputation: 41

async task is not Working in WorkManagers CallbackDispatcher

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 ?

Upvotes: 3

Views: 784

Answers (1)

Gazihan Alankus
Gazihan Alankus

Reputation: 12014

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;

Upvotes: 2

Related Questions