skip to Main Content

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


  1. 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:

    1. Define the Module in Koin Create a Koin module to provide the
      dependencies.

    val locationModule = module {
        single { LocationServices.getFusedLocationProviderClient(androidContext()) }
        single { 
            LocationTracker(
                fusedLocationProviderClient = get(),
                application = androidContext()
            )
        }
    }
    

    1. Start Koin in Your Application Class
      Initialize Koin in your Application class and include the module.

      class MyApp : Application() {
      override fun onCreate() {
      super.onCreate()

           // Start Koin
           startKoin {
               androidContext(this@MyApp)
               modules(locationModule)
           }
       }
      

      }


    1. Inject Dependencies
      Use Koin to retrieve LocationTracker or any other dependencies wherever needed.

      class MyActivity : AppCompatActivity() {
      private val locationTracker: LocationTracker by inject()

       override fun onCreate(savedInstanceState: Bundle?) {
           super.onCreate(savedInstanceState)
      
           // Use locationTracker
           locationTracker.startTracking()
       }
      

      }

    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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search