lazyReplace<P> static method

Future<void> lazyReplace<P>(
  1. InstanceBuilderCallback<P> builder, {
  2. String? tag,
  3. bool? fenix,
})

Lazily replaces an existing dependency with a new builder function.

This method preserves the permanence status of the original instance when replacing it with the new lazy builder.

Parameters:

  • builder: Function that creates the dependency when needed
  • tag: Optional tag to identify the specific instance to replace
  • fenix: If provided, overrides the original fenix setting

Throws an exception if the instance is not found.

Implementation

static Future<void> lazyReplace<P>(
  InstanceBuilderCallback<P> builder, {
  String? tag,
  bool? fenix,
}) async {
  try {
    // Get instance info to determine if it should be permanent
    final info = Get.getInstanceInfo<P>(tag: tag);
    final permanent = info.isPermanent ?? false;

    // Delete existing instance
    final deleted = await delete<P>(tag: tag, force: permanent);
    if (!deleted) {
      throw BindError<String>(
        controller:
            "Failed to delete existing instance before lazy replacement for ${P.toString()}",
        tag: tag,
      );
    }

    // Register the new lazy builder with appropriate fenix setting
    Get.lazyPut(
      builder,
      tag: tag,
      fenix: switch (fenix) {
        null =>
          permanent, // Default to permanent status if fenix not specified
        var value => value // Use provided value if specified
      },
    );
  } catch (e) {
    // Rethrow with more context if it's not already a BindError
    if (e is! BindError) {
      // Create a new error with the available information
      throw BindError<String>(
        controller:
            "Error replacing instance with lazy builder for type ${P.toString()}: ${e.toString()}",
        tag: tag,
      );
    }
    rethrow;
  }
}