restoreQueue method

Future<bool> restoreQueue()

Restore the queue from persistent storage. Returns true if successful.

Implementation

Future<bool> restoreQueue() async {
  debug('$runtimeType - Restoring User Task Queue');
  bool success = true;

  try {
    final snapshots = await Persistence().getUserTasks();

    // now create new AppTaskExecutors, initialize them, and add them to the queue
    for (var snapshot in snapshots) {
      AppTaskExecutor executor = AppTaskExecutor();

      // find the deployment based on the deployment id in the snapshot
      SmartphoneDeployment? deployment;
      if (snapshot.studyDeploymentId != null) {
        deployment = SmartPhoneClientManager()
            .getStudyRuntime(snapshot.studyDeploymentId!)
            ?.deployment;
      }
      if (deployment == null) {
        warning(
            '$runtimeType - Could not find deployment information based on snapshot: $snapshot');
      } else {
        executor.initialize(snapshot.task, deployment);

        // add the stream of measurements to the overall smartphone deployment controller
        // issue => https://github.com/cph-cachet/carp.sensing-flutter/issues/437
        SmartPhoneClientManager()
            .getStudyRuntime(snapshot.studyDeploymentId!)
            ?.executor
            .addMeasurements(executor.measurements);

        // now put the restored task back on the queue
        if (_userTaskFactories[executor.task.type] == null) {
          warning(
              '$runtimeType - Could not enqueue AppTask. Could not find a factory for creating '
              "a UserTask for type '${executor.task.type}'");
        } else {
          UserTask userTask =
              _userTaskFactories[executor.task.type]!.create(executor);
          userTask.id = snapshot.id;
          userTask.state = snapshot.state;
          userTask.enqueued = snapshot.enqueued;
          userTask.triggerTime = snapshot.triggerTime;

          _userTaskMap[userTask.id] = userTask;
          debug(
              '$runtimeType - Enqueued UserTask from loaded task queue: $userTask');
        }
      }
    }
  } catch (exception) {
    success = false;
    warning('$runtimeType - Failed to load task queue - $exception');
  }
  return success;
}