bloc
bloc copied to clipboard
[Feature Request] Hydrated blocs with different storages in the same app
From @ncuillery (original issue)
Is your feature request related to a problem? Please describe. I have some hydrated blocs that use the default temp folder (as a cache for my information coming the network: perform the fetching request only if the data is older than 12 hours). But I also would like to use a hydrated bloc using the shared preferences storage to store my user preferences such as language, newsletter optin, etc. I can't do that because, if I implement a custom storage in a BlocDelegate, all my blocs will use this storage.
Describe the solution you'd like I guess one solution would be to not using BlocDelegate for implementing custom storage. Or improve the BlocSupervisor/BlocDelegate API to allow multiple BlocDelegates.
Additional context I think I'd have the same problem if I already use a SimpleBlocDelegate for logging purpose and I want to write an other BlocDelegate for custom hydrated bloc storage.
cc @orsenkucher
Hello @felangel 👋
I think we can let the user provide the Storage
optionally to each HydratedBloc. And we can use the HydratedBloc.storage
as a fallback to all HydratedBloc
s if custom storage is not provided via the constructor.
The implementation will look like this:
mixin HydratedMixin<State> on BlocBase<State> {
late Storage _storage;
void hydrate([Storage? storage]) {
_storage = storage ?? HydratedBloc.storage;
try {
final stateJson = _toJson(state);
if (stateJson != null) {
_storage.write(storageToken, stateJson).then((_) {}, onError: onError);
}
} catch (error, stackTrace) {
onError(error, stackTrace);
}
}
}
abstract class HydratedBloc<Event, State> extends Bloc<Event, State>
with HydratedMixin {
HydratedBloc(State state, [Storage? storage]) : super(state) {
hydrate(storage);
}
}
This will be non-breaking, and calling the hydrate
method inside the bloc constructor will remain necessary for those who will use the mixin.