1+ package org.koin.compose.activity
2+
3+ import androidx.activity.ComponentActivity
4+ import androidx.activity.compose.LocalActivity
5+ import androidx.compose.runtime.Composable
6+ import androidx.compose.runtime.remember
7+ import org.koin.android.scope.AndroidScopeComponent
8+ import org.koin.core.annotation.KoinInternalApi
9+ import org.koin.core.parameter.ParametersDefinition
10+ import org.koin.core.qualifier.Qualifier
11+ import org.koin.core.scope.Scope
12+
13+ /* *
14+ * Resolves a Koin dependency from the current Activity's scope within a Composable context.
15+ *
16+ * This function retrieves dependencies that are scoped to the current [ComponentActivity].
17+ * The Activity must implement [AndroidScopeComponent] to provide its Koin scope.
18+ *
19+ * The resolved instance is remembered across recompositions as long as the qualifier,
20+ * scope, and parameters remain the same.
21+ *
22+ * @param T The type of the dependency to resolve.
23+ * @param qualifier Optional [Qualifier] to distinguish between multiple definitions of the same type.
24+ * @param scope The Koin [Scope] to resolve from. Defaults to the current Activity's scope.
25+ * The Activity must implement [AndroidScopeComponent], otherwise an error is thrown.
26+ * @param parameters Optional [ParametersDefinition] to pass dynamic parameters to the dependency.
27+ * @return The resolved instance of type [T].
28+ * @throws IllegalStateException if the current Activity does not implement [AndroidScopeComponent].
29+ *
30+ * @sample
31+ * ```
32+ * @Composable
33+ * fun MyScreen() {
34+ * val stateHolder: StateHolder = koinActivityInject()
35+ * // Use state holder...
36+ * }
37+ * ```
38+ *
39+ * @see AndroidScopeComponent
40+ * @see Scope
41+ */
42+ @OptIn(KoinInternalApi ::class )
43+ @Composable
44+ inline fun <reified T > koinActivityInject (
45+ qualifier : Qualifier ? = null,
46+ scope : Scope = ((LocalActivity .current as ComponentActivity ) as? AndroidScopeComponent )?.scope ? : error("Activity is not an AndroidScopeComponent "),
47+ noinline parameters : ParametersDefinition ? = null,
48+ ): T {
49+ val p = parameters?.invoke()
50+ return remember(qualifier, scope, p) {
51+ scope.getWithParameters(T ::class , qualifier, p)
52+ }
53+ }
0 commit comments