Search code examples
androiddependency-injectiondagger-hilt

Best way to use a Global String variable in Android App 2022?


I have a variable globalStringVar which I use throughout my application, including in different repositories in the app's data layer. I am trying to work out the best/cleanest way to pass this around my application.

Currently globalStringVar is instantiated in my Application() class. I then use Application().getAppInstance().myGlobalString in the repositories when I need to use it. I also update the variable in the repositories.

I feel like there is code smell here and a better way exists to store and use a global string variable. I tried to see if I could somehow inject the string using dagger/hilt but had no success. Does anybody have a better way of using global string variables?

@HiltAndroidApp
class Application : android.app.Application() {
    var globalStringVar = "Start Value"

    companion object {
        private lateinit var applicationInstance: Application
        @JvmStatic
        fun getAppInstance(): Application {
            return applicationInstance
        }
    }

    override fun onCreate() {
        super.onCreate()
        applicationInstance = this
    }
}
@Singleton
class MyRepo @Inject constructor() {

    fun updateValue() {
    Application.getAppInstance().globalStringVar = "Update Value"
    }

    /*other repo code*/
}


Solution

  • I have created my own custom class MyData() that holds globalString property.

    This can then be injected where necessary with Dagger/Hilt.

    class MyData() {
        var globalString: String = "Start Value"
    }
    
    @Module
    @InstallIn(SingletonComponent::class)
    object DataModule {
        @Singleton
        @Provides
        fun provideDataInstance(): MyData {
            return MyData()
        }
    }
    
    @Singleton
    class MyRepo @Inject constructor() {
        @Inject lateinit var myData: MyData
    
        fun updateValue() {
        myData.globalString = "Update Value"
        }
        /*other repo code*/
    }