Skip to content

Instantly share code, notes, and snippets.

@tfcporciuncula
Created July 15, 2018 04:17
Show Gist options
  • Save tfcporciuncula/238f6d662525e63cb85c65a74df18255 to your computer and use it in GitHub Desktop.
Save tfcporciuncula/238f6d662525e63cb85c65a74df18255 to your computer and use it in GitHub Desktop.
mediator-live-data-gist-3
class BooksViewModel(bookDao: BookDao) : ViewModel() {
private val booksAscending = bookDao.booksAscending()
private val booksDescending = bookDao.booksDescending()
val books = MediatorLiveData<List<Book>>()
private var currentOrder = ASCENDING
init {
books.addSource(booksAscending) { result ->
if (currentOrder == ASCENDING) {
result?.let { books.value = it }
}
}
books.addSource(booksDescending) { result ->
if (currentOrder == DESCENDING) {
result?.let { books.value = it }
}
}
}
fun rearrangeBooks(order: BooksOrder) = when (order) {
ASCENDING -> booksAscending.value?.let { books.value = it }
DESCENDING -> booksDescending.value?.let { books.value = it }
}.also { currentOrder = order }
}
@takieddine12
Copy link

Can you please provide the same code in java , i really need to achieve the same in my project , my project is all in java and i'm not familiar with kotlin yet thank you

@takieddine12
Copy link

takieddine12 commented Nov 23, 2019

this is what i did in my java code :

public void InitMediation(MvvmAdapter mvvmAdapter)
{
mediatorLiveData.addSource(getSortAlphabetically(), new Observer<List>() {
@OverRide
public void onChanged(List list) {
mvvmAdapter.UpdateRecycler(list);

        }
    });
}

** and this code in my main activity which supposdly should sort the data :
public void OrderATOZ() {
viewModel.InitMediation(mvvmAdapter);
}

i m working on todolist app with mvvm architecture , i would like to get the data sorted alphabetically when the user click on navigation drawer item , so when the user clicks , firstly the order data gets updated in the recycler and also to be shown order next launch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment