Hilt Dagger 2, Create instance of any object and injecting to a class

Published

I am converting my existing application to MVVM architecture, I use hilt dagger 2 for dependency injection. In my previous code I use single thread Executor to execute all tasks. Now in the Dependency Injection main Module I would like to create an instance of Executor and then inject it in all classes. Can someone check my approach if it’s good.

@Module
@InstallIn(SingletonComponent::class)
class AppModule {

    @Singleton
    @Provides
    fun getAppDb(context: Application) : AppDatabase {
        return AppDatabase.getInstance(context)
    }

    @Singleton
    @Provides
    fun getDao(appDb: AppDatabase) : StoragesDao {
        return appDb.storagesDao()
    }

    @Singleton
    @Provides
    fun getExecutor() : Executor {
        return Executors.newSingleThreadExecutor();
    }
}

StorageRepository Class where I inject executor instance

class StorageRepository @Inject constructor(
    @ApplicationContext val context: Context,
    private val storageDao: StoragesDao,
    private val executor: Executor
    ) {

  //  private val executor: Executor = Executors.newSingleThreadExecutor()

    fun insertStorage(storagesEntity: StoragesEntity, listener: OnApiUpdateListener?) {
        executor.execute {
            storageDao.insertAll(storagesEntity)
            if (ApiUtils.isNetworkAvailable(context)) {
                post_Storage(storagesEntity, listener)
            } else {
                listener?.eventUpdate(context.getString(R.string.failure))
            }
        }
    }
}

Source: Android Questions

Published
Categorized as android, dagger-2, dagger-hilt, dependency-injection, kotlin

Answers

Leave a Reply

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq