I’m migrating from Hilt
to Koin
.
With Hilt I’m doing the following for injecting LocationTracker
:
@Module
@InstallIn(SingletonComponent::class)
object LocationModule {
@Provides
@Singleton
fun providesFusedLocationProviderClient(application: Application): FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(application)
@Provides
@Singleton
fun providesLocationTracker(
fusedLocationProviderClient: FusedLocationProviderClient,
application: Application
): LocationTracker = LocationTracker(
fusedLocationProviderClient = fusedLocationProviderClient,
application = application
)
}
But with koin I don’t know how to inject Application
in order to be able to inject FusedLocationProviderClient
.
So, how can I inject Application
to end up injecting LocationTracker
???
2
Answers
In Koin, you can get the application instance using
androidApplication()
.https://insert-koin.io/docs/reference/koin-android/get-instances/#android-scope–android-context-resolution
When migrating from Hilt to Koin, you can use androidContext() provided by Koin to access the Application instance, which can then be used for dependency injection.
Here’s how you can migrate your LocationTracker injection setup from Hilt to Koin:
dependencies.
Start Koin in Your Application Class
Initialize Koin in your Application class and include the module.
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
}
Inject Dependencies
Use Koin to retrieve LocationTracker or any other dependencies wherever needed.
class MyActivity : AppCompatActivity() {
private val locationTracker: LocationTracker by inject()
}
Explanation
androidContext(): Provides the Application context to your Koin module.
single: Ensures a singleton instance for the dependencies.
get(): Resolves dependencies automatically when injecting into LocationTracker.
This setup ensures your migration from Hilt to Koin is smooth and retains the same dependency injection behavior. Let me know if you need help with other migrations!