Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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] 
            }
        }
    }
like image 590
Taki Avatar asked Jan 25 '26 22:01

Taki


1 Answers

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]
like image 85
hardartcore Avatar answered Jan 28 '26 11:01

hardartcore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!