-1

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))
            }
        }
    }
}
Amir Dora.
  • 2,831
  • 4
  • 40
  • 61

1 Answers1

1

It’s fine, although I do have few notes.

I would put the database into LocalPersistanceModule so I won't spam the App module with these dependencies. There will be more, like shared prefs. This will be especially useful if you are going to spam it with providesDao methods for every DAO.

I don't declare Provides DAO methods. When I declare something which wants DAOs, I will use the AppDatabase in the provide method to fetch required DAOs, and will pass them to the object.

The @Singleton for your provides methods adds overhead for both build and runtime.

I don't like the Context dependency in the repository at all. It is data layer; it doesn't care about a context and your localized strings.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Vladislav
  • 140
  • 5