Created
July 17, 2018 17:54
-
-
Save tfcporciuncula/e369d5f9263cf1bc1694b2aa20612e53 to your computer and use it in GitHub Desktop.
mediator-live-data-gist-2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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