Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go back to main-thread inside coroutine?

Im running this code since addListenerForSingleEvent is a long Running operation:

CoroutineScope(IO).launch {  
    userRef.addListenerForSingleValueEvent(object : ValueEventListener {
        override fun onCancelled(p0: DatabaseError) {

        }

        override fun onDataChange(p0: DataSnapshot) {
            if (p0.exists()) {
                withContext(Main) {
                    toggleLoading()
                    val intent = Intent(this@LogInActivity, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                }
            } else{
                withContext(Main) {
                    var addUsernameIntent = Intent(this@LogInActivity, 
                                             AddUsernameActivity::class.java)
                    startActivityForResult(addUsernameIntent, CHOOSE_USERNAME_REQUEST)
                }
            }
        }
   })
}   

I get an error where i write withContext(Main) that says :

Suspension functions can be called only within coroutine body

But I have a coroutine body right? Before i just had a Thread(runnable {..}) instead of a couroutine, but i read that i shouldn't do intents inside any other Thread than main-thread so i changed to coroutine.

like image 907
eek Avatar asked Jun 22 '26 17:06

eek


1 Answers

The Firebase client already runs any network and disk I/O operations on a separate thread. There almost never is a need to run addListenerForSingleEvent on a separate thread yourself.

Also see:

  • Do we need to use background thread for retrieving data using firebase?
  • Firebase Android: onDataChange() event always executed in Main UI Thread?
  • Firebase database - run on different thread
  • Call method in another thread on completion
like image 104
Frank van Puffelen Avatar answered Jun 25 '26 12:06

Frank van Puffelen



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!