Skip to content

Commit

Permalink
feat: added global di for non-android projects
Browse files Browse the repository at this point in the history
  • Loading branch information
y9san9 committed Jul 25, 2023
1 parent 8195ddd commit 4b873e8
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 11 deletions.
1 change: 1 addition & 0 deletions android/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ android {

dependencies {
api(projects.core)
implementation(projects.global)
}
25 changes: 16 additions & 9 deletions android/src/main/kotlin/app.meetacy.di.android/AndroidDI.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,28 @@ import android.app.Application
import app.meetacy.di.DI
import app.meetacy.di.builder.di
import app.meetacy.di.dependency.Dependency
import app.meetacy.di.android.di as globalDi
import app.meetacy.di.global.GlobalDI
import app.meetacy.di.global.di

lateinit var di: DI private set
val di: DI get() {
return try {
di
} catch (_: IllegalStateException) {
error("DI is not initialized, call AndroidDI.init(di)")
}
}

val DI.application: Application by Dependency

public object AndroidDI {
public fun inject(
object AndroidDI {
fun init(
application: Application,
di: DI
) {
if (::globalDi.isInitialized) error("DI can only be initialized once")

globalDi = di + di(checkDependencies = false) {
val application by constant(application)
}
GlobalDI.init(
di = di + di(checkDependencies = false) {
val application by constant(application)
}
)
}
}
9 changes: 9 additions & 0 deletions global/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
plugins {
id("kmp-library-convention")
}

version = libs.versions.mdi.get()

dependencies {
commonMainImplementation(projects.core)
}
15 changes: 15 additions & 0 deletions global/src/commonMain/kotlin/app/meetacy/di/global/GlobalDI.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package app.meetacy.di.global

import app.meetacy.di.DI

public val di: DI
get() = diSource ?: error("DI is not initialized, call GlobalDI.init(di)")

private var diSource: DI? = null

public object GlobalDI {
public fun init(di: DI) {
if (diSource != null) error("DI can only be initialized once")
diSource = di
}
}
2 changes: 1 addition & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ composeRuntime = "1.3.3"
composeCompiler = "1.4.4"
lifecycle = "2.6.1"

mdi = "0.0.23"
mdi = "0.0.24"

[libraries]

Expand Down
3 changes: 2 additions & 1 deletion settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ includeBuild("build-logic")
include(
"core",
"android",
"compose"
"compose",
"global"
)

0 comments on commit 4b873e8

Please sign in to comment.