I am writing an Android app that makes use of Firebase Auth and DI.
In this app, I regularly need to use the user's UID to perform some database operations, and in search of a way to stop passing the UID through MVVM layers, I've decided to give dependency injection a try.
My AppModule looks like this:
AppModule.kt
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun provideServer(@ApplicationContext c: Context) = Server(c, Volley.newRequestQueue(c), provideUid())
@Singleton
@Provides
fun provideFirebase() = FirebaseSource(FirebaseAuth.getInstance())
@Singleton
@Provides
fun provideFirebaseAuth() = Firebase.auth
@Singleton
@Provides
fun provideFirebaseUser(): Boolean {
return provideFirebaseAuth().currentUser != null
}
@Singleton
@Provides
// FIXME
fun provideUid(): String {
return provideFirebaseAuth().currentUser?.uid ?: ""
}
}
Function provideUid()
returns the Firebase current user's UID, and injects is as a dependency in a separate Server
class:
Server.kt (part of)
class Server @Inject constructor(
private val c: Context,
private val volleyRequestQueue: RequestQueue,
private val uid: String
): IServer {
When the app starts for the first time, Dagger Hilt uses this constructor and provides a null UID because there is no logged-in user at the moment. This behavior persists for the rest of the app's lifecycle, and the Server
class never has a non-null UID because it was already constructed with an empty UID as a property.
Restarting the app will construct the Server
class with a non-empty UID because Firebase Auth keeps some registry of the user's auth state.
My question, then, is whether Dagger Hilt can realize the UID has changed and update its value or not.
Things I've tried:
- Deleting the
@Singleton
annotation fromprovideUid()
- Changing the
Server
'suid
parameter fromval
tovar
.