Retrieve data from Android data store directly to variable

In the shared preference the developer can read the stored value directly and store it in a variable like this

  val score = sharedPref.getInt("highScore"), 0)
    
  Toast.makeText(requireContext(), score.toString(), Toast.LENGTH_SHORT).show() // The score variable can be accessed here

But in the data store it is not possible because it is inside the coroutine scope (inside Fragment)

  viewLifecycleOwner.lifecycleScope.launch {
  val score =  preferenceHelper.read("highScore")
  }
    
Toast.makeText(requireContext(), score.toString(), Toast.LENGTH_SHORT).show() // The score variable cannot be accessed here

One of the solutions presented in the documentation is to use runBlocking, but it should be avoided as much as possible

 val score = runBlocking { preferenceHelper.read("highScore") }

Toast.makeText(requireContext(), score.toString(), Toast.LENGTH_SHORT).show() // The score variable can be accessed here

My question is is there a better way than using runBlocking or should I keep using the shared preference ? :)

1 answer

  • answered 2022-05-04 09:57 Jakoss

    You can easily make your toast inside the coroutine you've created for the fragment. So your example is pretty much ok, just move the toast invocation inside the launch block and you'll be good to go.

    To answer directly the question - there is no better way of running suspend function synchronously. And, if the shared preferences are working you - you can stick to them just fine. But keep in mind that those are reading value on main thread, so it will be pretty much the same as reading from dataStore in runBlocking

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum