简体   繁体   中英

return int value from dataStore preferences

I have an application where I'm saving int value using datastore preferences, when I get the value, I execute the code and want to return that int value so that I can use it in different places in my code but could not figure it out, if anyone can help, thank you in advance

I tried to make a global member to assign that value and then return but since the value is returned asynchronously, it is crashing the app.

  • This is my code
private fun setTextSize() : Int {
        val dataStore = requireContext().createDataStore("textSize")
        lifecycleScope.launch { 
            dataStore.data.collect { 
              val textSize =  it[Common.TEXT_SIZE_PREFERENCE] 
            }
        }
    }

If you want to get the value directly you should use runBlocking . Something like this should do the trick:

val textSize = runBlocking { dataStore.data.first() }[Common.TEXT_SIZE_PREFERENCE]

You can add suspend modifier to your function and access it using CoroutineScope as

suspend fun setTextSize() = dataStore.data.firstOrNull()[Common.TEXT_SIZE_PREFERENCE] ?: -1

While accesing

lifeCycleScope.launch{
    val textSize = setTextSize()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM