I am building a common library module in KMM that requires android application context.
How can I pass it to common module manually?
I have seen answers using androidx.startup.InitializationProvider
which requires separate dependency.
I don't want any dependency.
Found a good solution using expect
/actual
mechanism of object
.
expect object AppContext
import android.content.Context
import java.lang.ref.WeakReference
actual object AppContext {
private var value: WeakReference<Context?>? = null
fun set(context: Context) {
value = WeakReference(context)
}
internal fun get(): Context? {
return value?.get()
}
}
actual object AppContext
class MyLibConfig(
val appContext: AppContext,
val isTestDevice: Boolean = false,
val isLogsEnabled: Boolean = false,
)
object MyLib {
fun initialize(config: MyLibConfig) {
val commonContext = config.appContext
}
}
override fun getMyLibDatabase(appContext: AppContext): SqlDriver {
return AndroidSqliteDriver(
my_lib_db.Schema,
appContext.get()!!,
"my_lib_db.sqlite"
)
}
MyLib.initialize(
MyLibConfig(
appContext = AppContext.apply { set(application.applicationContext) },
isTestDevice = true,
isLogsEnabled = true,
)
)