Roshan
Roshan

Reputation: 509

How to inject Kotlin extentsion properties using Dagger-Hilt

I'm trying to implement Proto Datastore using Kotlin serialization and Hilt.

Reference: https://medium.com/androiddevelopers/using-datastore-with-kotlin-serialization-6552502c5345

I couldn't inject DataStore object using the new DataStore creation syntax.

@InstallIn(SingletonComponent::class)
@Module
object DataStoreModule {

    @ExperimentalSerializationApi
    @Singleton
    @Provides
    fun provideDataStore(@ApplicationContext context: Context): DataStore<UserPreferences> {
        val Context.dataStore: DataStore<UserPreferences> by dataStore(
            fileName = "user_pref.pb",
            serializer = UserPreferencesSerializer
        )
        return dataStore
    }

}

I get the lint message Local extension properties are not allowed

How can inject this Kotlin extension property? Or is there any way to inject dataStore object?

Upvotes: 2

Views: 1722

Answers (1)

Samuel Eminet
Samuel Eminet

Reputation: 4737

You can't use extensions in a local context, you should call this way:

@InstallIn(SingletonComponent::class)
@Module
object DataStoreModule {

    @ExperimentalSerializationApi
    @Singleton
    @Provides
    fun provideDataStore(@ApplicationContext context: Context): DataStore<UserPreferences> =
         DataStoreFactory.create(
            serializer = UserPreferencesSerializer,
            produceFile = { context.dataStoreFile("user_pref.pb") },
        )
}

Upvotes: 2

Related Questions