When you know how to contruct a value in runtime it may be better to encode that than to serialize all the object state. This greatly reduces the amount of code that has to be generated and enables serialization of values that would not be possible otherwise.
For example, an API client may hold references to open sockets, attempting to serialize such a value will result in an error:
To solve this problem, wrap the construction of the value with a factory like so:
Now, instead of attempting to serialize the client, the factory will be serialized and the result of calling it will be exported:
factory
Define a factory for a value that should be constructed at runtime.
The value constructed by the factory is also available at build time like before, but it is only constructed once you try to use it:
This means that if the value is not used during build it will only be constructed at runtime.
asyncFactory
Similar to factory, this functions allows declaring how to construct a value at runtime. The key difference is that using asyncFactory the return value of the given factory function will be awaited.
This is useful when you want to load remote information upon initialization of your module, like loading credentials from a remote secret manager.
Will generate the following module:
Just like factory, the value can be used at runtime, but you need to pass the unawaited value to the module definition: