Skip to content

Commit

Permalink
add Jetpack Compose ViewModel factory retrieval
Browse files Browse the repository at this point in the history
  • Loading branch information
romainbsl committed Mar 31, 2023
1 parent 441fca7 commit b639595
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 4 deletions.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ plugins {

allprojects {
group = "org.kodein.di"
version = "7.19.0"
version = "7.19.1"
}
4 changes: 2 additions & 2 deletions doc/antora.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: kodein
title: Kodein
version: '7.19'
display_version: '7.19.0'
display_version: '7.19.1'
nav:
- modules/ROOT/nav.adoc
- modules/core/nav.adoc
Expand All @@ -11,6 +11,6 @@ nav:
asciidoc:
attributes:
branch: '7.19'
version: '7.19.0'
version: '7.19.1'
kotlin: '1.8.10'
jdk: '1.8'
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,35 @@ public inline fun <reified VM : ViewModel> rememberViewModel(tag: Any? = null):
}
)
}
}

/**
* Gets an instance of a [VM] as an android [ViewModel] for the given [tag].
*
* VM generic will be preserved!
*
* @param VM The type of the [ViewModel] to retrieve.
* @param tag The bound tag, if any.
* @return An instance of [VM].
* @throws DI.NotFoundException If no provider was found.
* @throws DI.DependencyLoopException If the value construction triggered a dependency loop.
*/
@Composable
public inline fun <reified A: Any, reified VM : ViewModel> rememberViewModel(tag: Any? = null, arg: A): ViewModelLazy<VM> = with(localDI()) {
val viewModelStoreOwner = LocalViewModelStoreOwner.current ?: error("")

remember {
ViewModelLazy(
viewModelClass = VM::class,
storeProducer = { viewModelStoreOwner.viewModelStore },
factoryProducer = {
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return direct.instance<A, VM>(tag, arg) as T
}
}
}
)
}
}
2 changes: 1 addition & 1 deletion settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ buildscript {
maven(url = "https://raw.githubusercontent.com/kosi-libs/kodein-internal-gradle-plugin/mvn-repo")
}
dependencies {
classpath("org.kodein.internal.gradle:kodein-internal-gradle-settings:7.0.5")
classpath("org.kodein.internal.gradle:kodein-internal-gradle-settings:7.0.6")
}
}

Expand Down

0 comments on commit b639595

Please sign in to comment.