Home > database >  Getting a List from Coroutines
Getting a List from Coroutines

Time:08-12

I try to make a method that would get a list of movies from database using coroutine and would return me that list. But as you know coroutine returns Deferred, not a list, so I have a problem here.

    suspend fun getMovieList(): List<MovieLocalModel>{
        val list = viewModelScope.async {
            dbRepository.getMovie().toList()
        }
        return list
    }

How can I convert Deferred List<MovieLocalModel to List<MovieLocalModel?

Or is there a method to get a list from LiveData?

CodePudding user response:

To get an object from Deffered you can use await method:

suspend fun getMovieList(): List<MovieLocalModel>{
    val list = viewModelScope.async {
        dbRepository.getMovie().toList()
    }
    return list.await()
}

If you use LiveData you can get an object using value property:

val list = livaDataObj.value

CodePudding user response:

If you don't have a reason this fetch needs to specifically be done in the viewModelScope, which is likely the case since it is only fetching something (not saving something), you can simplify this by calling the function directly.

suspend fun getMovieList(): List<MovieLocalModel> =
    dbRepository.getMovie().toList()
  • Related