CodeBlanks Logo Icon CodeBlanks

Summary - Background task

Combine callbackDispatcher and PeriodicTask to sync in background.

Sync flow

A sync flow combines callbackDispatcher and PeriodicTask. First the callback is registered with Workmanager().initialize, then the periodic sync task is scheduled with registerPeriodicTask. On every period callbackDispatcher is called and the sync runs based on the task id.

Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
Workmanager().registerPeriodicTask(
  'sync-task',
  'sync',
  frequency: Duration(minutes: 15),
);

Practice Write a sync flow

Write a top-level callbackDispatcher function that takes String task and returns true for the 'sync' id. In main, first register the callback with Workmanager().initialize, then schedule a task with registerPeriodicTask using id 'sync-task', callback name 'sync', and a 15 minute frequency, and print 'ok'.

Starter code

main.dart
class Workmanager {
  void initialize(Function dispatcher, {bool isInDebugMode = false}) {}
  void registerPeriodicTask(String uniqueId, String taskName, {required Duration frequency}) {}
}

// callbackDispatcher fonksiyonunu yaz
// String task parametresi alsın
// 'sync' kimliği için true döndürsün

void main() {
  // initialize ile callback kaydet
  // periyodik görevi zamanla
  // 'ok' yazdır
}

Sample solution

main.dart
class Workmanager {
  void initialize(Function dispatcher, {bool isInDebugMode = false}) {}
  void registerPeriodicTask(String uniqueId, String taskName, {required Duration frequency}) {}
}

bool callbackDispatcher(String task) {
  if (task == 'sync') {
    return true;
  }
  return false;
}

void main() {
  Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
  Workmanager().registerPeriodicTask(
    'sync-task',
    'sync',
    frequency: Duration(minutes: 15),
  );
  print('ok');
}

Expected output

ok

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In a sync flow, in which order are initialize and registerPeriodicTask called?

  • First initialize, then registerPeriodicTask Correct answer
  • Only initialize is enough
  • First registerPeriodicTask, then initialize
  • Both cannot be called at the same time

Explanation: First you register the callbackDispatcher with initialize, then schedule the task with registerPeriodicTask; otherwise the callback cannot be found.

2 Enable debug mode

Question
Workmanager().initialize(callbackDispatcher, ____: true);
Answer
Workmanager().initialize(callbackDispatcher, isInDebugMode: true);

Explanation: To enable debug mode in the initialize call, the isInDebugMode parameter is set to true.

3 Sync flow parts

Term Meaning
initialize Callback registration
registerPeriodicTask Periodic task
callbackDispatcher Background callback
frequency Repeat interval

All lessons in Advanced