How can I forward the context for multiple KMM lib...
# multiplatform
j
How can I forward the context for multiple KMM libraries?
I'm using Koin, but I'm not sure about the best approach to pass the app context until the shared prefs library.
m
You can’t use context in shared module, it has to be platform independent.
j
So in this case I have to keep forward the conext, right?
m
Can You elaborate a little more about your problem? It’s hard to understand it. Basically KMM app has to be built in such a way that shared codebase doesn’t know about platform specific objects. I guess that you want to implement shared local storage right? If so then You need to use expect/actual operators. Example of SQLDelight commonMain:
Copy code
expect class DbArgs       expect fun getSqlDriver(dbArgs: DbArgs?) : SqlDriver
androidMain
Copy code
actual class DbArgs(
    var context : Context
)

actual fun getSqlDriver(dbArgs: DbArgs?): SqlDriver {
   return AndroidSqliteDriver(dev_notary_db.Schema,dbArgs!!.context,"dev_notary_db")
}
j
I have a shared prefs (UserDefaults for iOS) library (kmm) that needs context In the app when starting I need to ask for a kmm module (init module), if the user has accepted some terms, this is stored in the prefs, this module uses a second module that is shared by others like a repository, here is used in the library. So I have to forward the context from : App -> Module(context) -> Repository(Context) -> Library (Context)
In Module, Repository, and Library I had
Copy code
expect class PlatformContext

actual typealias PlatformContext = Activity // Android

actual typealias PlatformContext = NSObject // iOS
that holds the context
m
You can create an Application() in shared module androidMain package which will have the context accessible. From there you can assign some variable that is in the shared module. You can create the expect class in commonMain that actual class in androidMain will require context.
j
Yeah Im using this, but for data store and keychain needs the context
p
Not sure if this is what you need, but if you define
Copy code
expect class Preferences {}
then in androidMain you can do:
Copy code
actual class Preferences(context:Context) {}
j
Undertand, but I will have to forward the context from : App -> Module(context) -> Repository(Context) -> Library (Context), right?
165 Views