androidkotlinandroid-jetpack-composestartup

How can I run a piece of code only once at the first start of the application in jetpack compose kotlin?


My question is about how can I run a piece of code only once at the first launch of the app in kotlin, jetpack-compose? I have, for instance, some list initializations which I want to perform only once at the first start but currently they are being run at every launch so the list are growing bigger each time. My desire is to run them only once so the list sizes be fixed. How can I do that? I've already found 3 similar questions but they are too old and many things are deprecated:

Run a piece of code only once at installation

Execute something just once per application start

Run code once at startup

Another example of action that can be performed only at the first launch is doing some setup choices, which might also be changed later. Thanks in advance.


Solution

  • If you are already using Room database then just save the list of items you want in a sqlite database and export it (.db). Then you can use that file to create a Room datbase that has that list of item you created as its initial data. createFromAsset will only run when there is no database yet in the phone so it will not duplicate.

    Room.databaseBuilder(
                context = context,
                klass = DictionaryDatabase::class.java,
                name = DictionaryDatabase.DATABASE_NAME
            ).createFromAsset("database/dictionary.db").fallbackToDestructiveMigration().build()
    

    or to make it simple you can just use a sharedPreference to determine if the list already populated with data

    val sharedPreferences = context.getSharedPreferences("APP", Context.MODE_PRIVATE)
    
    if (sharedPreferences.getBoolean("IS_LIST_POPULATED", false) == false) {
        // add items to your list
        
    
        // save preference that we already have the initial data of the list so we dont execute this block the next time
        val editor = sharedPreferences.edit()
        editor.putBoolean("IS_LIST_POPULATED", true)
        editor.apply()
        editor.commit()
    }