'How can I create a global object/service that can be used across my Viewmodels/controllers android

I am creating an app that is powered by firebase. I want to implement the firebase auth, which according to the documentation would require me to initialize the auth object and use it around the application:

    private lateinit var auth: FirebaseAuth
// ...
// Initialize Firebase Auth
auth = Firebase.auth

Is there a way to have the initialized auth object global, and probably lifecycle aware, so I can just use it anywhere I want across my app?

Please note I am new to android development/kotlin



Solution 1:[1]

There are different ways to do it. With Hilt you can provide it

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

    @Provides
    @Singleton
    fun providesFirebaseAuth(): FirebaseAuth =  Firebase.auth

And in your Activity

@AndroidEntryPoint
class SignUpActivity: AppCompatActivity() {
    @Inject
    lateinit var auth: FirebaseAuth
...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kingston