Skip to content

Commit

Permalink
Add ViewModel scope warnings &. deprecate API where it can use scope …
Browse files Browse the repository at this point in the history
…directly
  • Loading branch information
arnaudgiuliani committed Mar 5, 2024
1 parent 6f52ed5 commit 426c4f4
Show file tree
Hide file tree
Showing 4 changed files with 6 additions and 5 deletions.
7 changes: 3 additions & 4 deletions docs/reference/koin-android/scope.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,12 @@ If you try to access Scope from `onDestroy()` function, scope will be already cl

ViewModel is only created against root scope to avoid any leaking (leaking Activity or Fragment ...). This guard for the visibility problem, where ViewModel could have access to incompatible scopes.

:::note
If you ViewModel can't get access to a dependency, check in which scope it has been declared.
:::warn
ViewModel can't access to Activity or Fragment scope. Why? Because ViewModel is lasting long than Activity and Fragment, and then it would leak dependencies outside of proper scopes.
:::


:::note
If you _really_ need to bridge a dependency from outside a ViewModel scope, you can use "injected parameters" to pass some objects to your ViewModel.
If you _really_ need to bridge a dependency from outside a ViewModel scope, you can use "injected parameters" to pass some objects to your ViewModel: `viewModel { p -> }`
:::

`ScopeViewModel` is a new class to help work on ViewModel scope. This handle ViewModel's scope creation, and provide `scope` property to allow inject with `by scope.inject()`:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import org.koin.core.scope.Scope
import kotlin.reflect.KClass

@OptIn(KoinInternalApi::class)
@Deprecated("scope is not used for ViewModel creation. This will fallback to root scope.")
@KoinInternalApi
fun <T : ViewModel> resolveViewModelCompat(
vmClass: Class<T>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import kotlin.reflect.KClass
* @param parameters - for instance building injection
*/
@KoinInternalApi
@Deprecated("scope is not used for ViewModel creation")
@Deprecated("scope is not used for ViewModel creation. This will fallback to root scope.")
fun <T : ViewModel> resolveViewModel(
vmClass: KClass<T>,
viewModelStore: ViewModelStore,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ fun <T : ViewModel> Fragment.viewModelForClass(
}

@OptIn(KoinInternalApi::class)
@Deprecated("scope is not used for ViewModel creation. This will fallback to root scope.")
@MainThread
fun <T : ViewModel> getLazyViewModelForClass(
clazz: KClass<T>,
Expand Down

0 comments on commit 426c4f4

Please sign in to comment.