Skip to content

Instantly share code, notes, and snippets.

@tfcporciuncula
Created July 17, 2018 17:54
Show Gist options
  • Save tfcporciuncula/e369d5f9263cf1bc1694b2aa20612e53 to your computer and use it in GitHub Desktop.
Save tfcporciuncula/e369d5f9263cf1bc1694b2aa20612e53 to your computer and use it in GitHub Desktop.
mediator-live-data-gist-2
class BooksViewModel(bookDao: BookDao) : ViewModel() {
// the LiveData from Room won't be exposed to the view...
private val dbBooks = bookDao.books()
// ...because this is what we'll want to expose
val books = MediatorLiveData<List<Book>>()
private var currentOrder = ASCENDING
init {
// here our MediatorLiveData is basically a proxy to dbBooks
books.addSource(dbBooks) { result: List<Book>? ->
result?.let { books.value = sortBooks(it, currentOrder) }
}
}
fun rearrangeBooks(order: BooksOrder) = dbBooks.value?.let {
// and here we can set the value we want
books.value = sortBooks(it, order)
}.also { currentOrder = order }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment