Home > database >  How can I get data from ViewModel to Activity or Fragment in clean and simple way?
How can I get data from ViewModel to Activity or Fragment in clean and simple way?

Time:09-07

I have a question... sometimes, I need to get data from ViewModel directly. For example, Let's say there's a isChecked() method in ViewModel. And I want to use it in the if condition.

if(viewModel.isChecked()){
    // TODO:
}

So, what I am doing right now is:

fun isChecked(): Boolean = runBlocking {
    val result = dbRepo.getData()
    val response = apiRepo.check(result)
    return response.isSuccessful
}

It uses runBlocking. So, it runs on MainThread. I don't think it's a good way because it can freeze the screen. But yes, if the condition needs to run, it needs to wait it until it gets the data from DB and Network.

Another way that I can think of is using LiveData. However, I can't use it in the condition. So, I needs to move the condition in the observer block. But sometimes, this can't be done because there can be something before the condition. And it doesn't seem to look direct but writing code here and there and finally get that data.

So, Is there any simpler way than this?

CodePudding user response:

Use lifecyclescope.launch(Dispatcher.IO) instead of runblocking

CodePudding user response:

If you want to do work from Activity then use lifecycleScope otherwise viewModelScope for viewmodel. Launching Coroutines using withcontext will return results after suspending your long-running task on background

fun isChecked(): Boolean = viewModelScope.launch{
     val result =  withContext(Dispatchers.IO) { 
          longRunningTask() 
    }
    return result
}

private suspend fun longRunningTask(): Boolean {
    val result = dbRepo.getData()
    val response = apiRepo.check(result)
    return response.isSuccessful
}
  • Related