mirror of
https://github.com/venera-app/venera.git
synced 2025-09-27 15:57:25 +00:00
Improve init. Close #236
This commit is contained in:
40
lib/utils/init.dart
Normal file
40
lib/utils/init.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// A mixin class that provides a way to ensure the class is initialized.
|
||||
abstract mixin class Init {
|
||||
bool _isInit = false;
|
||||
|
||||
final _initCompleter = <Completer<void>>[];
|
||||
|
||||
/// Ensure the class is initialized.
|
||||
Future<void> ensureInit() async {
|
||||
if (_isInit) {
|
||||
return;
|
||||
}
|
||||
var completer = Completer<void>();
|
||||
_initCompleter.add(completer);
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
Future<void> _markInit() async {
|
||||
_isInit = true;
|
||||
for (var completer in _initCompleter) {
|
||||
completer.complete();
|
||||
}
|
||||
_initCompleter.clear();
|
||||
}
|
||||
|
||||
@protected
|
||||
Future<void> doInit();
|
||||
|
||||
/// Initialize the class.
|
||||
Future<void> init() async {
|
||||
if (_isInit) {
|
||||
return;
|
||||
}
|
||||
await doInit();
|
||||
await _markInit();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user