replace method
Overrides the factory function and refreshes the existing object using the new factory, if any.
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 is triggered for the old object.
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 removed and the disposer is triggered.
// A new object is immediately created by the new factory.
pot.replace(() => User(id: 200));
}
Tip
If you need to replace the factory only in tests, you may want
to use a non-replaceable pot and to use
replaceForTesting instead of this method.
It ensures that factory replacement is restricted to testing
and prevents its misuse in application logic. Conveniently,
replaceForTesting() is available even on a non-replaceable pot.
Implementation
void replace(PotObjectFactory<T> factory) => _replace(factory);