Help Instance Help

m8ty_persisted_queue

There are use cases where you application may be offline but you need to send the data to the server as soon as the server is available or after restart of the application. Here some examples:

  • Remote Logging

  • Tracking of user behaviour (Analytics)

Storage

Let's focus as first on storage options. You may store the data into shared_preferences, some files etc. In this package out of the box shared_preferences are supported.

abstract interface class IM8tyLocalStorage<E> { Future<void> saveList(List<E> data); Future<List<E>> load(); }

By implementing this interface you can use any available storage. M8tyLocalStorage<E> supports shared_preferences. Type E can be any type.

Serialization/Deserialization

As we are having instances of classes and in order to persist them, we need to serialize them to String or any other format required for persistence.

abstract interface class IM8tyItemsSerializer<E> { String serialize(List<E> items); List<E> deserialize(String? items); }

This interface gives us the option to serialize any object to String and to deserialize it back to the target class instance. Default implementation is M8tyItemsSerializer<E> which uses json serializer/deserializer behind the scenes. As dart is not using reflection, you can pass a converter function E Function(dynamic)? to this class. This converter function is used to convert the json string back to a class instance

final sharedPrefsStorage = M8tyLocalStorage<MyItem>( storageKey: kPersistentQueue, serializer: M8tyItemsSerializer<MyItem>(), );

Because of shared_preferences being used here, you need to provide a key used for the storage and the serializer converting the class instances into the String like described above.

Persisted queue

Future<PersistentQueue<Map<String, String>>> load() => PersistentQueue.load( storage: sharedPrefsStorage, );

Instance of PersistentQueue is created by using the sharedPrefsStorage. If there are any items already persisted, those will be loaded in this step.

Timer Based Queue

Sending of the data to the server should be done by using batch processing. This means that we are constantly adding data to the queue. Depending on the configured time options an upload to the server should be automatically done.

final persistedQueue = M8tyTimerBasedPersistentQueue<String>( timerDuration: const Duration(seconds: 1), queue: Queue.of(["myData"]), processAction: action, );

Parameter

Description

timerDuration

When the processAction should be executed

queue

It's any Queue type. It can be in memory or persisted queue

processAction

When timerDuration elapses, then processAction is being executed. All the items in the queue are passed in to the processAction. If processAction returns true, then the items are removed from the queue. In case of false, nothing will happen

Last modified: 12 October 2024