Home > Enterprise >  How to return value from coroutine / wait for coroutine to finish
How to return value from coroutine / wait for coroutine to finish

Time:11-08

I wrote function to return value from database, it works because i assign value to state and recomposition, but that is not proper way to interact with database.

      fun getUser():State<User?>{
        val id = sharedPrefs?.getString("uId", "")
        id?.let {
            if (it != "")
                runBlocking {
                    CoroutineScope(Dispatchers.IO).launch {
                        repository?.getUser(it)?.let {
                            currentUser.value = it
                            Log.v("user_1","" it)
                        }
                    }
                }
        }
        Log.v("user_2","" currentUser.value)
        return currentUser
    }

I thought runBlocking will make it work, but user_1 contains value and user_2 is null. So changes are visible only in coroutine which seems to be performed after return. I would be grateful if you can provide any good resource about coroutines.

CodePudding user response:

The correct way to do this is to use a suspend function and withContext instead of launch -- there are several other things I'd clean up in your code (eliminate almost all the ?.let), but this should do:

   suspend fun getUser():State<User?>{
        val id = sharedPrefs?.getString("uId", "")
        id?.let {
            if (it != "")
                withContext(Dispatchers.IO) {
                        repository?.getUser(it)?.let {
                            currentUser.value = it
                            Log.v("user_1","" it)
                        }
                }
        }
        Log.v("user_2","" currentUser.value)
        return currentUser
    }
  • Related