Hello guys! is there another way to return a value...
# coroutines
w
Hello guys! is there another way to return a value from a Coroutine without blocking the Main Thread? Maybe using Channels or Flow? . I'm getting an object from Room and I want to return a specific attribute from that object after get it.
⏸️ 3
s
Using coroutines allows you not to block the main thread. Do you have a sample/snippet?
w
Copy code
fun getDescription(code: String): String = runBlocking {
    val tour = localRepository.getTourByCode(code) // This is a Coroutine getting the Object from Room
    return@runBlocking tour.description
}
This is the snippet, is pretty simple. Yeah, I don't want to block the Main Thread, but, the process seems to be synchronous.
s
That is because of
runBlocking
. Don’t use this. Let me whip up a quick example based on your snippet…
w
If I send a context Dispatchers.IO to the
runBlocking
that will prevent to block the Main Thread? 🤔
Thanks @streetsofboston, yeah, exactly, but, to be able to return a value the function
getDescription(..)
should be synchronous, correct me if I'm wrong.
s
Copy code
class MyActivity: AppCompatActivity(), CoroutineScope by MainScope() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ...
        launch { 
            textView.text = getDescription("Desc")
        }
    }
    
    suspend fun getDescription(code: String): String {
        val tour = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { localRepository.getTourByCode(code) }
        return tour.description
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }
}