0
votes

I have a suspend method: checkIfAvailable() that returns a Boolean. I want to get that boolean value and then use it in my activity. I try this the following way(not sure if this is how it should be done):

suspend fun checkIfAvailable(year: Int): Boolean = viewModelScope.async{
        return@async dao.checkIfAvailable(year)
    }.await()

This returns a boolean. The problem is that i can't use that boolean, because the function must be a suspend function as await() must be called inside one.

How do i get the boolean value without blocking the main thread?

I tried it with runBlocking in my activity:

fun something(tag: Int): Boolean {
            return runBlocking {
            return@runBlocking checkIfAvailable(tag)
        }
}

but this crashes or blocks the mainthread.

I just need a way to get the value out of the suspend function and into a variable without blocking the thread.

1
It is not possible. You can't make a blocking (i.e. time-consuming) task magically return a result immediately. You must put your code that reacts to the result of this check in the coroutine. - Tenfour04
why not use LiveData object if you are using ViewModel, that way you'll be properly notified of a new change when observing that particular livedata (Boolean in this case) - DarShan

1 Answers

0
votes

Use this inside your activity:

lifecycleScope.launch(Dispatchers.Default) {
      val result = checkIfAvailable(year)
}