Is there a suggested way to provide an Android Con...
# multiplatform
l
Is there a suggested way to provide an Android Context where needed in a multiplatform project? I'm using SQLDelight right now, which needs a context for creating a DB factory on Android, but not iOS or other platforms, but other libraries could have similar use cases in the future.
Right now, the best I can think of has a method that sets up a koin module with platform-dependent objects. Is this a good way to do this? Is there a better way?
t
I would make a common factory interface to get SQLDelight set up. Something you can pass any common dependencies into. Then for each platform, implement this interface. The platform factory object’s constructor can accept platform specific things like Context. The platform side builds this factory, and makes it accessible to common code, potentially through Koin though you may not need to go that far. Then common code can use this factory to pass in any common dependencies.
Dependency injection can get hairy on multiplatform, unless you’re leaning on constructor injection. Koin can be helpful in the android specific objects. But in typical Koin fashion, I recommend leaning as much on constructor injection as possible, and use the framework only when absolutely necessary.
j
fwiw https://github.com/joreilly/PeopleInSpace is using the Koin platform modules approach to handle exactly this
❤️ 1
🙌 2
l
I’m trying to minimize the amount of code I have to write in the Android and iOS apps. What I did for now was to set up an init function in androidMain that takes a Context and one in iosMain that currently doesn’t take anything, then call them in Application#onCreate and the iOS equivalent. The init methods set up a Koin module. I’ll take a look at how People in Space is set up.
t
We are using https://developer.android.com/topic/libraries/app-startup within the androidMain module. This allows to provide the Android Context without any additional code in the android and iOS apps! The Context can then be put into your DI modules as you like.
l
I didn’t know that existed. That would make for a cool KMM library if there’s a good iOS equivalent.