Singleton in Android

Hi, so apparently using static variables in android can cause some problems, the most important one being the fact that the variable can lose it’s value when application is in background.

So what about variables in Kotlin’s objects or companion objects ?

You can try reading the bytecode. Kotlin objects are just implemented as Java static variables. In the end they are still only saved in the same Java runtime (not really Java on Android, but the principle is the same), not anywhere on the disk.

You should read Android documentation, but as far as I remember, runtime can clear memory of any background application. Anything not parcelized could be erased.The same goes for kotlin object. Also you should remember that storing something but caches in global variables or singletons is a bad practice and should be avoided.

Ok thanks for the clarifications, and what about storing enum functions in companion objects? like ‘enumFromChar(c: Char): AnEnum’
or static functions in general ? I know kotlin’s extension functions are basically static functions

You are mixing state and functions. Even if runtime erases the state, it does not erase the code, or more specifically, code is being loaded every time you load the application.

To put it the other way, the functions get defind every time the application is loaded.

When we say that you shouldn’t store data in static/object properties, we are just saying that changes on the property will not be stored over time.

Suppose you have this object:

object MyObject {
    val version = 123
    var checks = 0
}

If you run this code every time your MainActivity is created:

MyObject.checks++
Toast.makeText(this, "We are running version ${MyObject.version}. Checked ${MyObject.checked} times", Toast.LENGTH_LONG).show()

before anyone/any bots complains about no translation, this is just an example

You will constantly get “We are running version 123” even after your app is restarted. This is because we defined version = 123 when the MyObject class gets loaded (which gets unloaded every time the app gets restarted/destroyed or whatever). So in case the data in MyObject gets erased, it gets set again before you use it the next time.

On the other hand, “Checked x times” will increase by one every time the user goes back to MainActivity, but it resets every time. This is because MyObject.checks also gets erased and set again, but as you can see from the code, it always runs MyObject.checks = 0, so it always starts again with 0.

1 Like