Skip to content

Commit 024e7bc

Browse files
committed
feat: Encoder and Decoder can return a Future
1 parent ef0da16 commit 024e7bc

File tree

3 files changed

+16
-8
lines changed

3 files changed

+16
-8
lines changed

lib/src/interface/storage.dart

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
/// Convert [T] to type that can be persisted in [Storage].
2-
/// This used in [Storage.write].
3-
typedef Encoder<T> = Object? Function(T);
1+
import 'dart:async';
2+
3+
/// Convert [T] to a value of type that can be persisted in [Storage].
4+
/// This is used in [Storage.write].
5+
typedef Encoder<T> = FutureOr<Object?> Function(T t);
46

57
/// Convert storage persisted type to [T].
6-
/// This used in [Storage.read].
7-
typedef Decoder<T> = T Function(Object?);
8+
/// This is used in [Storage.read].
9+
typedef Decoder<T> = FutureOr<T> Function(Object? o);
810

911
/// A persistent store for simple data. Data is persisted to disk asynchronously.
1012
abstract class Storage<Key extends Object, Options> {

test/fake_storage.dart

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ class FakeStorage implements StringKeyStorage {
6666

6767
Future<void> _setValue(String key, Object? value) {
6868
return _wrapCanThrows(() {
69+
assert(value is! Future<dynamic>, 'Actual type is ${value.runtimeType}');
70+
6971
if (value is List<String>?) {
7072
_map[key] = value?.toList();
7173
} else {
@@ -96,7 +98,8 @@ class FakeStorage implements StringKeyStorage {
9698
Future<void> write<T extends Object>(
9799
String key, T? value, Encoder<T?> encoder, [void _]) =>
98100
Future<void>.delayed(const Duration(milliseconds: 10))
99-
.then((_) => _setValue(key, encoder(value)));
101+
.then((_) => encoder(value))
102+
.then((encoded) => _setValue(key, encoded));
100103

101104
@override
102105
Future<Map<String, Object?>> reload() {

test/utils/user.dart

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,15 @@ extension RxStoreageExtensionsForUser on RxStorage<String, void> {
4848
Stream<User?> observeUser() => observe<User>('User', jsonStringToUser);
4949
}
5050

51-
User? jsonStringToUser(Object? s) {
51+
Future<User?> jsonStringToUser(Object? s) async {
52+
await Future<void>.delayed(const Duration(milliseconds: 10));
53+
5254
if (s == null) {
5355
return null;
5456
}
5557
final map = jsonDecode(s as String) as Map<String, Object?>;
5658
return User.fromJson(map);
5759
}
5860

59-
String? userToJsonString(User? u) => u == null ? null : jsonEncode(u);
61+
Future<String?> userToJsonString(User? u) async =>
62+
u == null ? null : jsonEncode(u);

0 commit comments

Comments
 (0)