replace method

void replace(
  1. PotObjectFactory<T> factory
)

Replaces the factory in a replaceable pot with a new one, and/or creates a new object using the new factory.

This behaves differently depending on the existence of the object.

If no object has been created:

  • Only the factory is replaced.
  • A new object is not created.
  • The disposer is not triggered.
final pot = Pot.replaceable(() => User(id: 100));

void main() {
  // The factory is replaced.
  // The pot has no User object yet.
  pot.replace(() => User(id: 200));

  // The object is created.
  final user = pot();

  print(user.id); // 200
}

If the pot has an object:

  • Both the factory and the object are replaced.
  • The disposer of the old object is triggered.
final pot = Pot.replaceable<User>(
  () => User(id: 100),
  disposer: (user) => user.dispose(),
);

void main() {
  // The object is created.
  pot.create();

  // The factory is replaced.
  // The existing object is discarded and the disposer is triggered.
  // A new object is immediately created by the new factory.
  pot.replace(() => User(id: 200));
}

If replacements are only necessary for testing, it is safer to make ReplaceablePot.replace unavailable by using a non-replaceable pot. You can use replaceForTesting on a non-replaceable pot instead if Pot.forTesting is set to true.

Implementation

void replace(PotObjectFactory<T> factory) => _replace(factory);