getOrCreate

inline fun <A : ViewModelStoreOwner, Component : Any> A.getOrCreate(key: Any = Component::class, noinline create: (context: BlocContext) -> Component): Lazy<Component>

Use this from an Activity or a Fragment to get or create a "Component" without directly involving a ViewModel, e.g.:

val component by getOrCreate { MyComponent(it) }      // it is the BlocContext

or:

val bloc by getOrCreate { bloc<Int, Int>(it, 2) { ... } }

Any class that needs a BlocContext to be instantiated is considered a "Component" in the context of this function.

The component will be tied to a ViewModel which is created transparently.

Parameters

key

As default Component::class is used as key to store and retrieve the component from the InstanceKeeper (which is tied to the ViewModel). Because all Bloc instances have the same class (its generic types have been erased), all Blocs would be stored with the same key. If we're using multiple Blocs tied to the same ViewModel (e.g. multiple fragments using different Blocs), we need to provide a key that identifies the Bloc. E.g.:

val listBloc by getOrCreate("blocList") { listBloc(it) }
val detailBloc by getOrCreate("detailBloc") { detailBloc(it) }

Alternatively a bloc can be wrapped into a concrete class in which case Component::class would work again as key.