Home > Software design >  Is using companion object in activity and application class a good way?
Is using companion object in activity and application class a good way?

Time:10-05

I used a lot of static data in Activities, Adapters, Application, etc with like

companion object{
    const val SEND_MY_DATA = "sendta"
    const val SEND_MY_DATA_1 = "sendta1"
    const val SEND_MY_DATA_2 = "sendta2"
}

to have common name for intent extras to match the same name between two activities. So, this static data are used in the activity & in another activity, and even some adapters.

And also I used this in Application class like

// this is used somewhere.
fun updateContext(){
    appContext = applicationContext
}

companion object{
    var appContext: Context? = null

    fun myFunction(context: Context){
        // use context param here.
    }
}

Is this a bad approach or not? Is there any better way to improve this?

CodePudding user response:

Just a note about saving data in the Application class, I encountered this by dealing with local resources in Room.
Generally, as in the case of the linked question, it can be a good solution (Android Studio shows a memory leak warning).
According to your needs you have to be careful to save data in this way, because Android OS can actually kill processes, including your Application instance.

To determine which processes should be killed when low on memory, Android places each process into an "importance hierarchy" based on the components running in them and the state of those components.

Check Processes and Application Lifecycle for more information.
A complete discussion about this can be found on this post.

CodePudding user response:

If you're going to make a static application Context reference, I think this is cleaner:

companion object {
    lateinit var context: Context
        private set
}

override fun onCreate() {
    super.onCreate()
    context = applicationContext
}

But if you use dependency injection, you shouldn't need it. The singleton Context pattern makes unit testing difficult.

As for storing your constants, companion objects are fine. They do result in an extra class that's compiled, but that should be trivial since you shouldn't have very many activities.

  • Related