Android compose preferences DataStore and manual Dependency Injection

111 views Asked by At

I created a SettingsRepository in my Application class.

private const val USER_PREFERENCES_NAME = "myapp_preferences"
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
    name = USER_PREFERENCES_NAME
)

class MyApplication : Application() {
    lateinit var container: AppContainer
    lateinit var settingsRepository: SettingsRepository

    override fun onCreate() {
        super.onCreate()

        container = DefaultAppContainer()
        settingsRepository = SettingsRepository(dataStore)
    }
}

Now I'm trying to move this repository inside my AppContainer following the manual DI practices suggested in documentation, the relevant code of my AppContainer looks like this.-

private const val USER_PREFERENCES_NAME = "myapp_preferences"

interface AppContainer {
    val settingsRepository: SettingsRepository
}

class DefaultAppContainer : AppContainer {
    private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
        name = USER_PREFERENCES_NAME
    )

    override val settingsRepository: SettingsRepository by lazy {
        SettingsRepository(dataStore)
    }
}

But the compiler keeps complaining in this line.-

SettingsRepository(dataStore)

with an unresolved reference error for dataStore, more specifically:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: private final val Context.dataStore: DataStore defined in com....data.DefaultAppContainer

Since I'm kind of rusty with Kotlin, I'm guessing I'm missing a simple workaround for this, but I'm a bit lost here, any help will be much appreciated (I'm aware I could just go for Hilt, but I rather letting it as a last resource, as it seems a bit too much for my simple project).

0

There are 0 answers