Jetpack Compose

Oct 11 2022 Kotlin 1.7.10, Android 13, Android Studio Chipmunk

Part 3: Manage State with Compose

15. Use the MVVM Pattern

Episode complete

Play next episode

Next
Save for later
About this episode
See versions

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 14. Add Animations to Compose Next episode: 16. Move Operations to ViewModels

The student materials have been reviewed and are updated as of September 2022.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Intro

[Slide 1 - Declarative patterns]

Demo

Most of the ViewModels are already predefined for you, but there’s one that you’ll build yourself. Create a new file called BookReviewDetailsViewModel, and add the following code:

@HiltViewModel
class BookReviewDetailsViewModel @Inject constructor(
  private val repository: LibrarianRepository
) : ViewModel() {

}
private val _bookReviewDetailsState = MutableLiveData<BookReview>()
val bookReviewDetailsState: LiveData<BookReview> = _bookReviewDetailsState

private val _genreState = MutableLiveData<Genre>()
val genreState: LiveData<Genre> = _genreState

private val _deleteEntryState = MutableLiveData<ReadingEntry>()
val deleteEntryState: LiveData<ReadingEntry> = _deleteEntryState

private val _isShowingAddEntryState = MutableLiveData<Boolean>(false)
val isShowingAddEntryState: LiveData<Boolean> = _isShowingAddEntryState

private val _screenAnimationState = MutableLiveData<BookReviewDetailsScreenState>()
val screenAnimationState: LiveData<BookReviewDetailsScreenState> = _screenAnimationState
fun setReview(bookReview: BookReview) {
  _bookReviewDetailsState.value = bookReview

  viewModelScope.launch {
    _genreState.value = repository.getGenreById(bookReview.book.genreId)
  }
}
private val bookReviewDetailsViewModel by viewModels<BookReviewDetailsViewModel>()