putAsync<T> static method
Registers an async instance with first-registrant-wins semantics.
Behavior:
- If a build is already in-flight for this (Type::tag), we await it and then return the resulting instance (we are a borrower).
- If already registered, we return the existing instance (borrow).
- Otherwise we mark ourselves as the creator, register the in-flight
future in
_inFlight, track it on the current scope, and await it.
Regardless of who finishes later, only one instance gets registered, and this scope’s cleanup will delete it iff this scope was the creator.
Implementation
static Future<T> putAsync<T>(AsyncInstanceBuilderCallback<T> builder, {String? tag, bool permanent = false}) async {
final key = _key<T>(tag);
// If someone is already installing (even if not yet "registered"), wait for them
final inflight = _inFlight[key];
if (inflight != null) {
await inflight; // borrower waits
return _awaitReady<T>(tag: tag); // borrow from creator
}
// If already registered, just borrow immediately
if (Get.isRegistered<T>(tag: tag)) {
return _awaitReady<T>(tag: tag);
}
// We are the first registrant: create a completer we can track
final completer = Completer<void>();
_inFlight[key] = completer.future;
// Record ownership right now (so dispose() knows we own it)
_active?.ownInstance<T>(tag: tag);
try {
// Start the real install and ensure our scope waits for it on dispose
final fut = Get.putAsync<T>(builder, tag: tag, permanent: permanent);
// Track keyed future so dispose can attach a late-delete hook (prevents leaks)
_active?.trackForKey(key, fut.then((_) {}));
final res = await fut;
return res;
} finally {
// Release waiters (success or error), then clear the in-flight slot
if (!completer.isCompleted) completer.complete();
_inFlight.remove(key);
}
}