Skip to content

Instantly share code, notes, and snippets.

@callmephil
Last active January 15, 2024 08:24
Show Gist options
  • Save callmephil/762a544f9dbb1786caed698af17aed04 to your computer and use it in GitHub Desktop.
Save callmephil/762a544f9dbb1786caed698af17aed04 to your computer and use it in GitHub Desktop.
In Memory Store (Article Example)
import 'dart:async';
void main() {
final authRepo = AuthenticationRepository();
// listen to cache updates
authRepo.user.listen((event) => print(event));
const user = User(firstName: 'John', lastName: 'Doe', age: 29);
// Create user
authRepo.createUser(user);
Future.delayed(const Duration(milliseconds: 100), () {
// Value is cached, nothing to print.
authRepo.updateUser(user.copyWith(firstName: 'John'));
});
Future.delayed(const Duration(milliseconds: 150), () {
authRepo.updateUser(user.copyWith(firstName: 'Jane'));
});
}
class AuthenticationRepository {
AuthenticationRepository({CacheClient? cache})
: _cache = cache ?? CacheClient();
final CacheClient _cache;
static const _cacheKey = 'unique_key';
Stream<User> get user {
return _cache.cacheUpdates
.where((cache) => cache.containsKey(_cacheKey))
.map((cache) => cache[_cacheKey] as User);
}
void createUser(User user) {
_cache.write<User>(key: _cacheKey, value: user);
}
void updateUser(User user) {
_cache.write<User>(key: _cacheKey, value: user);
}
}
class CacheClient {
CacheClient() : _cache = <String, Object>{};
final Map<String, Object> _cache;
final _cacheUpdatesController =
StreamController<Map<String, Object>>.broadcast();
Stream<Map<String, Object>> get cacheUpdates =>
_cacheUpdatesController.stream;
void write<T extends Object>({required String key, required T value}) {
if (_cache[key] == value) {
return;
}
_cache[key] = value;
_cacheUpdatesController.add(_cache);
}
T? read<T extends Object>({required String key}) {
final value = _cache[key];
if (value is T) return value;
return null;
}
void dispose() {
_cacheUpdatesController.close();
}
}
class User {
const User({required this.firstName, required this.lastName, this.age});
final String firstName;
final String lastName;
final int? age;
User copyWith({
String? firstName,
String? lastName,
int? age,
}) {
return User(
firstName: firstName ?? this.firstName,
lastName: lastName ?? this.lastName,
age: age ?? this.age,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is User &&
other.firstName == firstName &&
other.lastName == lastName &&
other.age == age;
}
@override
int get hashCode => firstName.hashCode ^ lastName.hashCode ^ age.hashCode;
@override
String toString() => 'User: $firstName $lastName, $age';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment