Skip to content

Commit

Permalink
fix: nav controller added to di.viewmodel
Browse files Browse the repository at this point in the history
  • Loading branch information
y9san9 committed Feb 18, 2024
1 parent 9ba33ef commit 19cbf87
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ import app.meetacy.di.dependency.Dependency
public val DI.navController: NavController by Dependency

@PublishedApi
internal val LocalNavController: ProvidableCompositionLocal<NavController> =
compositionLocalOf {
error("Please call `buildNavigationDI(...)` only inside `NavigationScreen { ... }`")
}
internal val LocalNavController: ProvidableCompositionLocal<NavController?> = compositionLocalOf { null }

@Composable
public fun NavigationScreen(
Expand All @@ -28,10 +25,12 @@ public fun NavigationScreen(
}

@Composable
public fun buildNavigationDI(di: DI): DI {
public fun buildNavigationDI(base: DI): DI {
val navController = LocalNavController.current

return di + di {
val navController by constant(navController)
return base + di {
val navController by provider {
navController ?: error("Please call `buildNavigationDI(...)` only inside `NavigationScreen { ... }`")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import androidx.compose.runtime.Composable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.meetacy.di.DI
import app.meetacy.di.builder.DIBuilder
import app.meetacy.di.android.compose.navigation.buildNavigationDI
import app.meetacy.di.builder.di
import app.meetacy.di.dependency.Dependency
import app.meetacy.di.factory.create
import app.meetacy.di.factory.factory0
import kotlinx.coroutines.CoroutineScope
import kotlin.reflect.typeOf

Expand Down Expand Up @@ -59,10 +58,12 @@ public inline fun <reified T1, reified T2, reified T3, reified T4, reified T5, r

@Composable
public inline fun <reified T : Any> DI.viewModel(crossinline factory: DI.() -> T): T {
val navigationDI = buildNavigationDI(base = this)

return androidx.lifecycle.viewmodel.compose.viewModel<DIViewModel<T>>(key = "${typeOf<T>()}") unused@ {
val vm = object : DIViewModel<T>() {}

val di = this@viewModel + di {
val di = navigationDI + di {
val viewModelScope by provider { vm.viewModelScope }
}

Expand Down
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ composeCompiler = "1.5.6"
androidxNavigation = "2.7.7"
lifecycle = "2.6.1"

mdi = "0.0.34"
mdi = "0.0.35"

[libraries]

Expand Down

0 comments on commit 19cbf87

Please sign in to comment.