我的问题是如何在 kotlin、jetpack-compose 中首次启动应用程序时仅运行一段代码一次?例如,我有一些列表初始化,我只想在第一次启动时执行一次,但目前它们在每次启动时运行,因此列表每次都会变得更大。我的愿望是只运行它们一次,以便固定列表大小。我怎样才能做到这一点?我已经找到了 3 个类似的问题,但它们太旧了,而且很多东西都已被弃用:
只能在第一次启动时执行的操作的另一个示例是进行一些设置选择,这些选择也可能在以后更改。预先感谢。
如果您已经在使用 Room 数据库,则只需将所需的项目列表保存在 sqlite 数据库中并将其导出 (.db)。然后,您可以使用该文件创建一个 Room 数据库,其中包含您创建的项目列表作为其初始数据。 createFromAsset 仅当手机中还没有数据库时才会运行,因此不会重复。
Room.databaseBuilder(
context = context,
klass = DictionaryDatabase::class.java,
name = DictionaryDatabase.DATABASE_NAME
).createFromAsset("database/dictionary.db").fallbackToDestructiveMigration().build()
或者为了简单起见,您可以使用共享首选项来确定列表是否已填充数据
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()
}