【问题标题】:async task is not Working in WorkManagers CallbackDispatcher异步任务不在 WorkManagers CallbackDispatcher 中工作
【发布时间】:2021-01-04 12:25:09
【问题描述】:

我正在将 WorkManager 用于后台服务。我的代码如下

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;
   
  });
}

有什么方法可以等待 executeTask 中的异步方法?

【问题讨论】:

    标签: flutter asynchronous flutter-plugin


    【解决方案1】:

    异步化非异步事物的方法是通过完成者。您创建一个完成者,等待它的未来并在未来完成它。

    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;
    
    

    【讨论】:

    • 刚刚将上面的await uploadCompleter.future; 添加到uploadCompleter.complete();,这对我来说非常有效。谢谢@GazihanAlankus
    • 我很高兴它有帮助,但我不明白 :) 如果你在uploadCompleter.complete(); 之前await uploadCompleter.future;,它永远不会到达uploadCompleter.complete();,对吧?
    • 我也很震惊,因为从概念上讲这是错误的,但它对我有用。
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2012-05-18
    相关资源
    最近更新 更多