Home > Software engineering >  get Result of method inside viewModelScope
get Result of method inside viewModelScope

Time:04-29

I am new to mvvm. So I want to ask how to retrieve the result of the method executed in viewModelScope. In my example I want to save a book in database and retrieve the saved book. Is there a better way to do it?

fun addBook (book:Book): BookEntity {
    var bookEntity = BookEntity()
    viewModelScope.launch {
        bookEntity = repository.addBook(book)
    }
    return bookEntity
}

CodePudding user response:

The coroutine, launched in addBook method using launch builder, will be executed after the function returns, so bookEntity will no be reassigned with a new value from DB. You should think about how you want to use the data. If you want it to be used just as an input data for some another calculations then it make sense to make the addBook() function suspend:

suspend fun addBook(): BookEntity {
    val bookEntity = repository.addBook(book) // I assume function repository.addBook(book) is suspend
    return bookEntity
}

If you want it to be displayed in UI you can make it suspend like above and call it in a coroutine using lifecycleScope:

in Activity/Fragment

lifecycleScope.launch {
    val book = viewModel.addBook()
    // update UI
}

Another alternative is to apply reactive approach using LiveData or Kotlin Flow

  • Related