Skip to content

Add offline persistence support #1032

Closed

Description

@rrousselGit

Riverpod should allow simple integration with offline storage solutions

A possibility is to have Riverpod serialize/deserialize the current state of a provider and send that to a database, associated with a unique key corresponding to the provider.

Activity

  1. added this to the milestone on Dec 31, 2021
  2. JulianBissekkou commented on Jan 11, 2022

    @JulianBissekkou

    This sounds interesting. I might give this a try.
    Do you already have an idea in mind? If so can you share some classes I should look into to be able to implement a draft for this functionality?

  3. rrousselGit commented on Jan 11, 2022

    @rrousselGit
    OwnerAuthor

    👋 thanks for offering to help, but this specific issue is in a bit of a unique position. I'd like to personally take care of this one

  4. self-assigned this
    on Jan 11, 2022
  5. huang12zheng commented on Jan 23, 2022

    @huang12zheng

    I don't know if it's gonna be bad,
    But I would say, you might want to take a look https://github.com/flutterdata/flutter_data
    or
    https://flutterdata.dev/docs/repositories/#architecture-overview
    deps

    Finally, thank you for your library : )
    (Translated above)

  6. rrousselGit commented on Jan 29, 2022

    @rrousselGit
    OwnerAuthor

    This feature is not really related to what you're suggesting

    What this issue involves will most likely be two bits:

    • new parameters on providers for decoding/encoding:

      final provider = SomeProvider(
        (ref) {},
        name: 'unique_key',
        decode: (data) => MyClass.fromJson(data),
        encode: (value) => value.toJson(),
      );
    • a way to tell ProviderScope/ProviderContainer how to obtain the encoded value of a provider

      ProviderScope(
        initialData: {
          'unique_key': { <some json> },
        },
        encoder: SomeDBEncoder(),
      ),
  7. ken-ng-esotec commented on Mar 5, 2022

    @ken-ng-esotec

    this sounds very interesting, is this being added to the roadmap? @rrousselGit

  8. chimon2000 commented on Mar 17, 2022

    @chimon2000

    this sounds very interesting, is this being added to the roadmap? @rrousselGit

    It is on the roadmap for https://github.com/rrousselGit/river_pod/milestone/1

  9. North101 commented on Mar 19, 2022

    @North101

    You mentioned this issue in #1168 and while the scope of this feature doesn't seem as narrow as just restoring the state after the OS kills your app, I thought you might be interested in this lib I recently made that restores the state of providers:
    https://github.com/North101/flutter_riverpod_restorable

  10. dJani97 commented on Mar 20, 2022

    @dJani97

    @North101 the repo link does not work, so I'll leave a link to your package:

    https://pub.dev/packages/flutter_riverpod_restorable

  11. tim-smart commented on Apr 1, 2022

    @tim-smart

    I needed a solution for a generic riverpod persistence layer, and ended up with this:

    https://github.com/tim-smart/riverpod_persistence/blob/main/test/riverpod_persistence_test.dart

    Would be nice to have something official!

  12. Reprevise commented on Apr 9, 2022

    @Reprevise

    Personally, I really like how states_rebuilder handles state persistence. This lets the user choose how offline data is stored while at the same time, abstracting away the actual storing of the data unless they want to. This solution would also help to mitigate any potential migration issues as the developer would be able to use their existing local storage provider.

  13. rrousselGit commented on Jul 31, 2022

    @rrousselGit
    OwnerAuthor

    That state_rebuild persistence wiki looks very similar to what I plan on doing for Riverpod. Thanks for sharing!

  14. rrousselGit commented on Aug 4, 2022

    @rrousselGit
    OwnerAuthor

    Supporting ChangeNotifier and the current StateNotifier may be difficult though.

    I think I'll have to implement this feature only for the new StateNotifier syntax if that's OK.

  15. 54 remaining items

  16. MarlonJD commented on Jun 25, 2024

    @MarlonJD

    @rrousselGit Wouldn't it be enough if we give a warning in the debug console when there is a change in state controller that will change the database?

  17. rrousselGit commented on Jun 25, 2024

    @rrousselGit
    OwnerAuthor

    I'm not concerned about updating data. Supporting modifying an existing provider should be straightforward.

    My only concern is about deleting a provider.

    When we delete a provider from the codebase, Riverpod has currently no way of knowing that it was removed.
    From Riverpod's PoV, the provider could still be there and it just hasn't been used by the application yet.

    So there's no way for Riverpod to do anything when a provider is deleted.

  18. rrousselGit commented on Jun 25, 2024

    @rrousselGit
    OwnerAuthor

    When using build_runner, we can solve that. Build_runner enables the generation of a list that contains all providers in the application. Then, Riverpod can compare that list with the DB's state and deduce what was removed.

    But macros won't allow app-wide code-generation. So we won't be able to generate such a list.

  19. MarlonJD commented on Jun 25, 2024

    @MarlonJD

    @rrousselGit What if we add desired offline supported providers to a list something called offline support list on provider scope, then checking that list?

  20. rrousselGit commented on Jun 26, 2024

    @rrousselGit
    OwnerAuthor

    It's tedious and error prone. You can easily forget to list one of such provider. And the linter wouldn't be able to help here.

  21. masreplay commented on Jul 14, 2024

    @masreplay

    Here is my fix
    https://pub.dev/packages/riverpod_cache

    import 'package:riverpod_cache/riverpod_cache.dart';
    
    @riverpod
    SharedPreferences sharedPreferences(SharedPreferencesRef ref) {
      throw UnimplementedError();
    }
    
    @riverpod
    Stream<TodoResponse> todo(TodoRef ref) {
      return ref.cacheFirstOfflinePersistence(
        key: 'todo',
        future: () async {
          await Future.delayed(const Duration(seconds: 2));
          final response = await Dio().get(
            'https://jsonplaceholder.typicode.com/todos/1',
          );
    
          final result = TodoResponse.fromJson(response.data);
    
          return result;
        },
        sharedPreferences: ref.read(sharedPreferencesProvider),
        fromJson: TodoResponse.fromJson,
        toJson: (object) => object.toJson(),
      );
    }
    
    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      final sharedPreferences = await SharedPreferences.getInstance();
      runApp(
        ProviderScope(
          overrides: [
            sharedPreferencesProvider.overrideWithValue(sharedPreferences),
          ],
          child: const MainApp(),
        ),
      );
    }
  22. MarlonJD commented on Jul 19, 2024

    @MarlonJD

    Is there any way to restart app when app was detached? After 15-20 min later or OS decided to exit the app, it gives us empty states and not even restarting app, I just tested with developer setting "don't keep activities" app starts give errors and its not getting normal state without exit the app and restart again, its huge issue, Is there any idea to handle this situation @rrousselGit ?

  23. rrousselGit commented on Sep 21, 2024

    @rrousselGit
    OwnerAuthor

    I wonder if instead of:

    @Riverpod(offline: true)
    class Counter extends _$Counter {
      int build() => 0;
    }

    We could have:

    @riverpod
    class Counter extends _$Counter {
      int build() => 0;
    }
    
    ...
    
    ProviderScope(
      offline: [counterProvider],
      child: MyApp(),
    );

    Although I don't like the split of the provider logic ; this could enable ProviderScope to automatically manage data migration.

  24. rrousselGit commented on Sep 23, 2024

    @rrousselGit
    OwnerAuthor

    Dealing with migration is delaying this feature by way too much.
    I've decided to:

    • Only include an "expiracy" Duration in Riverpod itself
    • push the responsibility of Data migration to whatever database you may use.

    Let's ship something and move forward. We can revisit later if need be.

  25. MarlonJD commented on Sep 23, 2024

    @MarlonJD

    Hey @rrousselGit, I think the same it's a right decision, btw what do you think about the #1032 (comment) this issue, how can we resolve this?

  26. rrousselGit commented on Sep 27, 2024

    @rrousselGit
    OwnerAuthor

    @MarlonJD this feels a bit off topic, so I'm not sure how to answer that.


    For now I'm thinking about having a Notifier-only initial release, with the following API:

    @Riverpod()
    @JsonPersist() // < Extra generator, which generates added logic to use from/toJson.
    class ModelNotifier extends _$ModelNotifier {
      @override
      Model build() => Model();
    }
    
    ...
    
    ProviderScope(
      persist: SQLiteRiverpodPersist(<some parameters>),
    )

    I may add support for non-notifier providers later, but this feels more natural for an initial release.

    The main value of notifiers is that we can override a bunch of methods in there, without making the API for this overly complex.
    It also makes supporting non-code-generation simpler. For example:

    class PersonNotifier extends Notifier<int> {
      @override
      Person build() => Person(name: 'John', age: 42);
    
      @override
      String get persistKey => 'my_table_name';
      @override
      Person decode(covariant String json) => Person.fromJson(jsonDecode(json));
      @override
      String encode(Person value) => jsonEncode(value.toJson());
    }
  27. Shiba-Kar commented on Nov 4, 2024

    @Shiba-Kar

    dam !! I was going to annotate @JsonPersist() in m code base and call it a day ! ....

  28. added a commit that references this issue on Feb 11, 2025
    9d206d3
  29. rrousselGit commented on Feb 11, 2025

    @rrousselGit
    OwnerAuthor

    Done in dev. We're getting close to a 3.0 release :)

    The API changed slightly from the previously mentioned proposal. We instead have a few things:

    1. Ref now has Ref.isFirstBuild. This gives Notifiers enough information to implement offline persistence on their own from scratch if they wanted to ; as that was the main missing piece.
      If folks are unsatisfied with Riverpod's high-level API, this would enable them to write their own.

    2. Notifiers can be persisted by mix-in Persistable, then using persist(...) in their build method:

    class Example extends AsyncNotifier<User> with Persistable<User, KeyT, ValueT> {
      @override
      Future<User> build() async {
        await persist(
          storage: /* An instance of Storage, an interface that enables Riverpod to communicate with a DB */
          key: /* An instance of KeyT, as specified in the mixin. This is generally a string, such as "Example" here */
          decode: (ValueT value) => User.fromValue(value), /* your typical fromJson */
          encode: (User user) => user.toValue(), /* your toJson */,
          // optional:
          options: StorageOptions(destroyKey: ..., cacheTime: ...),
        );
      }
    }

    Riverpod is agnostic from how objects are encoded/decoded. Although most people will likely use from/toJson, some may want protobuff or custom encoding protocols. Hence the generic KeyT/ValueT :)

    When using code-gen, only storage needs to be specified:

    @riverpod
    @JsonPersist() // We tell Riverpod to use from/toJson to encode the notifier
    class Example extends _$Example {
      @override
      Future<User> build() async {
        await persist(storage: ...);
      }
    }

    Note that @JsonPersist is experimental. It currently does the bare minimum to support JSON.
    It was either that or asking users to use two parts (like in Freezed) for JSON support. So Freezed users would end-up with:

    part 'file.riverpod.dart';
    part 'file.freezed.dart';
    part 'file.g.dart';

    I don't like that, so a limited JSON support was offered instead. We'll see what can be done about it in the future.

    1. An AsyncValue.isFromCache

    This new property gives information about whether the value was obtained from the database or not. It enables
    the UI to differentiate persisted data from server data

    1. A new riverpod_sqflite package is added.

    This is an official SQFlite support in Riverpod. It offers a custom Storage subclass with JSON support.

    The expected usage is:

    final storageProvider = FutureProvider<JsonSqFliteStorage>((ref) async {
      // Initialize SQFlite. We should share the Storage instance between providers.
      return JsonSqFliteStorage.open(
        join(await getDatabasesPath(), 'riverpod.db'),
      );
    });
    
    class Example extends AsyncNotifier<User> with Persistable<User, String, String> {
      @override
      Future<User> build() async {
        await persist(
          storage: ref.watch(storageProvider.future),
          // TODO pass other arguments
        );
      }
    }

    This is just a sneak peek. All of that will be explained properly in the documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions