Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make sure value returned from coroutine overwrites default value in android kotlin

I would like to make sure queried value from database comes always later than default value.

For example

class SetTimeFragment : Fragment(){

    private lateinit var binding: FragmentSetTimeBinding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = FragmentSetTimeBinding.inflate(layoutInflater, container, false)

        val dbId = 3
        val defaultTime = LocalTime.now().toString()

        //Set default value
        binding.timeView.setText(defaultTime)


        lifecycleScope.launchWhenCreated {

            val itemList = withContext(Dispatchers.IO) {

                //This is Database query
                ObjectBox.store.boxFor(Data::class.java)[dbId]
            }

            // string from database e.g.12:30
            val newTime = itemList.dbTimeStr

            //overwrite default value with database query result
            binding.timeView.setText(newTime)
        }


        return binding.root
    }

} 

Currently, this code has no problem. But does coroutine possibly return value faster than default value? I mean, database value goes to view first, and default value overwrites it. If it possibly happens, how can I prevent it? Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The coroutine doing the DB query is not even started when the default value is set on the text view, so there is no risk it can finish before that and write a value that would be overwritten by the default

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading