Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(hydrated_bloc): use user provided storage in hydrated cubit #2578

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions packages/hydrated_bloc/lib/src/hydrated_bloc.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:meta/meta.dart';

/// {@template hydrated_bloc}
/// Specialized [Bloc] which handles initializing the [Bloc] state
Expand Down Expand Up @@ -37,8 +37,8 @@ import 'package:hydrated_bloc/hydrated_bloc.dart';
abstract class HydratedBloc<Event, State> extends Bloc<Event, State>
with HydratedMixin {
/// {@macro hydrated_bloc}
HydratedBloc(State state) : super(state) {
hydrate();
HydratedBloc(State state, [Storage? storage]) : super(state) {
hydrate(storage);
}

/// Setter for instance of [Storage] which will be used to
Expand Down Expand Up @@ -79,8 +79,8 @@ abstract class HydratedBloc<Event, State> extends Bloc<Event, State>
abstract class HydratedCubit<State> extends Cubit<State>
with HydratedMixin<State> {
/// {@macro hydrated_cubit}
HydratedCubit(State state) : super(state) {
hydrate();
HydratedCubit(State state, [Storage? storage]) : super(state) {
hydrate(storage);
}
}

Expand Down Expand Up @@ -108,6 +108,9 @@ abstract class HydratedCubit<State> extends Cubit<State>
/// * [HydratedCubit] to enable automatic state persistence/restoration with [Cubit]
///
mixin HydratedMixin<State> on BlocBase<State> {
/// The [Storage] for the current instance of this class.
late Storage _currentStorage;

/// Populates the internal state storage with the latest state.
/// This should be called when using the [HydratedMixin]
/// directly within the constructor body.
Expand All @@ -120,12 +123,14 @@ mixin HydratedMixin<State> on BlocBase<State> {
/// ...
/// }
/// ```
void hydrate() {
final storage = HydratedBloc.storage;
void hydrate([Storage? storage]) {
_currentStorage = storage ?? HydratedBloc.storage;
try {
final stateJson = _toJson(state);
if (stateJson != null) {
storage.write(storageToken, stateJson).then((_) {}, onError: onError);
_currentStorage
.write(storageToken, stateJson)
.then((_) {}, onError: onError);
}
} catch (error, stackTrace) {
onError(error, stackTrace);
Expand All @@ -136,10 +141,10 @@ mixin HydratedMixin<State> on BlocBase<State> {

@override
State get state {
final storage = HydratedBloc.storage;
if (_state != null) return _state!;
try {
final stateJson = storage.read(storageToken) as Map<dynamic, dynamic>?;
final stateJson =
_currentStorage.read(storageToken) as Map<dynamic, dynamic>?;
if (stateJson == null) {
_state = super.state;
return super.state;
Expand All @@ -161,12 +166,13 @@ mixin HydratedMixin<State> on BlocBase<State> {
@override
void onChange(Change<State> change) {
super.onChange(change);
final storage = HydratedBloc.storage;
final state = change.nextState;
try {
final stateJson = _toJson(state);
if (stateJson != null) {
storage.write(storageToken, stateJson).then((_) {}, onError: onError);
_currentStorage
.write(storageToken, stateJson)
.then((_) {}, onError: onError);
}
} catch (error, stackTrace) {
onError(error, stackTrace);
Expand Down Expand Up @@ -317,7 +323,7 @@ mixin HydratedMixin<State> on BlocBase<State> {
/// [clear] is used to wipe or invalidate the cache of a [HydratedBloc].
/// Calling [clear] will delete the cached state of the bloc
/// but will not modify the current state of the bloc.
Future<void> clear() => HydratedBloc.storage.delete(storageToken);
Future<void> clear() => _currentStorage.delete(storageToken);

/// Responsible for converting the `Map<String, dynamic>` representation
/// of the bloc state into a concrete instance of the bloc state.
Expand Down
83 changes: 81 additions & 2 deletions packages/hydrated_bloc/test/hydrated_bloc_test.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// ignore_for_file: invalid_use_of_protected_member
import 'dart:async';
import 'package:test/test.dart';

import 'package:bloc/bloc.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:mocktail/mocktail.dart';
import 'package:bloc/bloc.dart';
import 'package:pedantic/pedantic.dart';
import 'package:test/test.dart';
import 'package:uuid/uuid.dart';

class MockStorage extends Mock implements Storage {}
Expand Down Expand Up @@ -75,6 +76,21 @@ class MyHydratedBloc extends HydratedBloc<int, int> {
int? fromJson(Map<String, dynamic> json) => json['value'] as int?;
}

class MyHydratedBlocWithCustomStorage extends HydratedBloc<int, int> {
MyHydratedBlocWithCustomStorage(Storage storage) : super(0, storage);

@override
Stream<int> mapEventToState(int event) async* {}

@override
Map<String, int>? toJson(int state) {
return {'value': state};
}

@override
int? fromJson(Map<String, dynamic> json) => json['value'] as int?;
}

class MyMultiHydratedBloc extends HydratedBloc<int, int> {
MyMultiHydratedBloc(String id)
: _id = id,
Expand Down Expand Up @@ -471,5 +487,68 @@ void main() {
));
});
});

group('MyHydratedBlocWithCustomStorage', () {
setUp(() {
HydratedBloc.storage = null;
});

test('should call storage.write when onChange is called', () {
const expected = <String, int>{'value': 0};
const change = Change(currentState: 0, nextState: 0);
MyHydratedBlocWithCustomStorage(storage).onChange(change);
verify(() => storage.write('MyHydratedBlocWithCustomStorage', expected))
.called(2);
});

test('should call onError when storage.write throws', () {
runZonedGuarded(() async {
final expectedError = Exception('oops');
const change = Change(currentState: 0, nextState: 0);
final bloc = MyHydratedBlocWithCustomStorage(storage);
when(
() => storage.write(any(), any<dynamic>()),
).thenThrow(expectedError);
bloc.onChange(change);
await Future<void>.delayed(const Duration(milliseconds: 300));
verify(() => bloc.onError(expectedError, any())).called(2);
}, (error, _) {
expect(
(error as BlocUnhandledErrorException).error.toString(),
'Exception: oops',
);
expect((error).stackTrace, isNotNull);
});
});

test('stores initial state when instantiated', () {
MyHydratedBlocWithCustomStorage(storage);
verify(
() => storage.write('MyHydratedBlocWithCustomStorage', {'value': 0}),
).called(1);
});

test('initial state should return 0 when fromJson returns null', () {
when<dynamic>(() => storage.read(any())).thenReturn(null);
expect(MyHydratedBlocWithCustomStorage(storage).state, 0);
verify<dynamic>(() => storage.read('MyHydratedBlocWithCustomStorage'))
.called(1);
});

test('initial state should return 101 when fromJson returns 101', () {
when<dynamic>(() => storage.read(any())).thenReturn({'value': 101});
expect(MyHydratedBlocWithCustomStorage(storage).state, 101);
verify<dynamic>(() => storage.read('MyHydratedBlocWithCustomStorage'))
.called(1);
});

group('clear', () {
test('calls delete on storage', () async {
await MyHydratedBlocWithCustomStorage(storage).clear();
verify(() => storage.delete('MyHydratedBlocWithCustomStorage'))
.called(1);
});
});
});
});
}
94 changes: 91 additions & 3 deletions packages/hydrated_bloc/test/hydrated_cubit_test.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import 'dart:async';
import 'package:test/test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';

import 'package:bloc/bloc.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
import 'package:uuid/uuid.dart';

class MockStorage extends Mock implements Storage {}
Expand Down Expand Up @@ -76,6 +77,16 @@ class MyMultiHydratedCubit extends HydratedCubit<int> {
int? fromJson(dynamic json) => json['value'] as int?;
}

class MyHydratedCubitWithCustomStorage extends HydratedCubit<int> {
MyHydratedCubitWithCustomStorage([Storage? storage]) : super(0, storage);

@override
Map<String, int> toJson(int state) => {'value': state};

@override
int? fromJson(dynamic json) => json['value'] as int?;
}

void main() {
group('HydratedCubit', () {
late Storage storage;
Expand Down Expand Up @@ -272,6 +283,83 @@ void main() {
});
});

group('MyHydratedCubitWithCustomStorage', () {
setUp(() {
HydratedBloc.storage = null;
});

test('should throw StorageNotFound when storage is null', () {
expect(
() => MyHydratedCubitWithCustomStorage(),
throwsA(isA<StorageNotFound>()),
);
});

test('should call storage.write when onChange is called', () {
final transition = const Change<int>(currentState: 0, nextState: 0);
final expected = <String, int>{'value': 0};
MyHydratedCubitWithCustomStorage(storage).onChange(transition);
verify(
() => storage.write('MyHydratedCubitWithCustomStorage', expected),
).called(2);
});

test('should throw BlocUnhandledErrorException when storage.write throws',
() {
runZonedGuarded(
() async {
final expectedError = Exception('oops');
final transition = const Change<int>(
currentState: 0,
nextState: 0,
);
when(
() => storage.write(any(), any<dynamic>()),
).thenThrow(expectedError);
MyHydratedCubitWithCustomStorage(storage).onChange(transition);
await Future<void>.delayed(const Duration(seconds: 300));
fail('should throw');
},
(error, _) {
expect(
(error as BlocUnhandledErrorException).error.toString(),
'Exception: oops',
);
expect(error.stackTrace, isNotNull);
},
);
});

test('stores initial state when instantiated', () {
MyHydratedCubitWithCustomStorage(storage);
verify(
() => storage.write('MyHydratedCubitWithCustomStorage', {'value': 0}),
).called(1);
});

test('initial state should return 0 when fromJson returns null', () {
when<dynamic>(() => storage.read(any())).thenReturn(null);
expect(MyHydratedCubitWithCustomStorage(storage).state, 0);
verify<dynamic>(() => storage.read('MyHydratedCubitWithCustomStorage'))
.called(1);
});

test('initial state should return 101 when fromJson returns 101', () {
when<dynamic>(() => storage.read(any())).thenReturn({'value': 101});
expect(MyHydratedCubitWithCustomStorage(storage).state, 101);
verify<dynamic>(() => storage.read('MyHydratedCubitWithCustomStorage'))
.called(1);
});

group('clear', () {
test('calls delete on storage', () async {
await MyHydratedCubitWithCustomStorage(storage).clear();
verify(() => storage.delete('MyHydratedCubitWithCustomStorage'))
.called(1);
});
});
});

group('MultiHydratedCubit', () {
test('initial state should return 0 when fromJson returns null', () {
when<dynamic>(() => storage.read(any())).thenReturn(null);
Expand Down