1

I'm facing an issue, like if my repository injected was not a Singleton.

I have a repository (in reality many, but let's make it simple) marked as @Singleton

@Module
@InstallIn(SingletonComponent::class)
class AppModule {
    @Provides
    @Singleton
    fun provideSettingsRepository(@ApplicationContext context: Context): SettingsRepository {
        return SettingsRepositoryImpl(context)
    }
}

Here the implementation of my repository :

class SettingsRepositoryImpl(context: Context) : SettingsRepository {
    private var _flow = MutableStateFlow("init value")
    override fun getFlow(): StateFlow<String?> = _flow.asStateFlow()
    
    override fun setMyValue(value:String) {
        _flow.value = value
    }
}

When I use it apart of my service (in some viewModels or others class with DI), it work perfectly. Today I implemented an AIDL service and wanted to do some DI. I had to use field injection because the service constructor has to be empty. It seems like the update made from my application isen't reported on my "TestApplication" who consume the Service (like if I had two instance of my repository).

Here the code of my service :

@AndroidEntryPoint
class AppService : Service()  {
    @Inject lateinit var settingsRepository: SettingsRepository

    fun someActionOnMyRepository() {
        settingsRepository.setMyValue("whatever")
    }
}

When I set the value from my UI (viewModel or any other class who as the repository injected), it's not updated in my service. The flow doesn't contains the new value (tested by debug or logcat).

I'm expecting my settingsRepository to be a singleton. What am I missing ? Is it because the field injection ?

Best regards

1 Answer 1

0

Ok, the problem was not from Hilt but about how i declared my service in my AndroidManisfest.xml

<service android:name=".services.MyAppService"
            android:process=":remote" <----- THIS
            android:exported="true">

Making it like that make it on another process. That mean it's like another app instance (so no more Singleton / SharedPreferences).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.