Created
June 7, 2024 06:57
-
-
Save buehler/c00d89bb1776f5be5e8f0a821be33756 to your computer and use it in GitHub Desktop.
Lazy and AsyncLazy initializator for Dart / Flutter applications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
class AsyncLazy<T> { | |
static final _cache = Expando(); | |
final FutureOr<T> Function() _factory; | |
final FutureOr Function(T)? _valueDispose; | |
const AsyncLazy(this._factory, [this._valueDispose]); | |
bool get isInitialized => _cache[this] != null; | |
FutureOr<T> call() async { | |
_cache[this] ??= await _factory(); | |
return _cache[this] as T; | |
} | |
Future dispose() async { | |
if (!isInitialized) { | |
return; | |
} | |
await _valueDispose?.call(await this()); | |
_cache[this] = null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Lazy<T> { | |
static final _cache = Expando(); | |
final T Function() _factory; | |
final void Function(T)? _valueDispose; | |
const Lazy(this._factory, [this._valueDispose]); | |
bool get isInitialized => _cache[this] != null; | |
T call() { | |
_cache[this] ??= _factory(); | |
return _cache[this] as T; | |
} | |
void dispose() { | |
if (!isInitialized) { | |
return; | |
} | |
_valueDispose?.call(this()); | |
_cache[this] = null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment