withSideEffect method
Creates a new factory that performs a side effect after object creation.
This is useful for logging, metrics, or other observability needs without modifying the core creation logic.
sideEffect: A function that receives the created object and performs a side effect
Returns a new ObjectFactory that performs the side effect after creation
Example:
final factory = ObjectFactory<Connection>(() => Connection());
// Add logging side effect
final loggedFactory = factory.withSideEffect((connection) {
print('Created new connection: ${connection.id}');
metrics.recordConnectionCreated();
});
Implementation
Future<ObjectFactory<T>> withSideEffect(void Function(T) sideEffect) async {
Future<ObjectHolder<T>> create([args]) async {
final result = await get(args);
sideEffect(result.getValue());
return result;
}
return SimpleObjectFactory<T>(([args]) => create(args));
}