Tarun Bidaliya
Tarun Bidaliya

Reputation: 1

Why the "isValid" boolean is not updating its value, even though the Log statement is executing properly inside this coroutine scope

private fun getuser() {
        if(!TextUtils.isEmpty(binding?.emailLogin?.editText?.text.toString()) && !TextUtils.isEmpty(binding?.passwordLogin?.editText?.text.toString())){
            var isvalid = false
            CoroutineScope(Default).launch {
                userlist = userViewModel.allusersList()
                val email = binding?.emailLogin?.editText?.text.toString()
                val pass = binding?.passwordLogin?.editText?.text.toString()
                for(user in userlist){
                    if(user.name == email && user.pass == pass){
                        Log.d("Validity", "Valid User")
                        isvalid = true
                    }
                }
            }
if(isvalid){
   Toast.makeText(this@Login_Fragment.requireContext(), "Valid 
    User",Toast.LENGTH_LONG).show()
            
      }
        
    }

}

So my question here is can we update any variable's value (which is declared outside the scope of coroutine's) inside the coroutine's scope?

Upvotes: 0

Views: 297

Answers (1)

Narendra_Nath
Narendra_Nath

Reputation: 5185

This is a concurrency problem. By the time the control is in if(isvalid){ line the data has not come back from the coroutine scope ..you need to use a with context block for eg



    private fun getuser() {
            if(!TextUtils.isEmpty(binding?.emailLogin?.editText?.text.toString()) && !TextUtils.isEmpty(binding?.passwordLogin?.editText?.text.toString())){
                var isvalid = false
                CoroutineScope(Default).launch {
                    userlist = userViewModel.allusersList()
                    val email = binding?.emailLogin?.editText?.text.toString()
                    val pass = binding?.passwordLogin?.editText?.text.toString()
                    for(user in userlist){
                        if(user.name == email && user.pass == pass){
                            Log.d("Validity", "Valid User")
                            isvalid = true
                        }
                    }
                     withContext(Dispatchers.Main){
    if(isvalid){
       Toast.makeText(this@Login_Fragment.requireContext(), "Valid 
        User",Toast.LENGTH_LONG).show()
                
          }
    }
                }
    
            
        }
    
    }

Upvotes: 0

Related Questions