How can I randomize a LiveData<list<StudentEntity>>
in a ViewModel
and display the results in my RecyclerView
? I was thinking I could do a
Collection.shuffle(Arrays.asList(myList))
but I don't believe this changes the order of the objects in the LiveDatalist.
MyFragment
....
public void RandomizeListOrder() {
mMainActivityViewModel.setRandomOrder();
adapter.notifyDataSetChanged();
}
ViewModel
private LiveData<List<StudentEntity>> mStudentList
public void setRandomOrder() {
Collection.shuffle(Arrays.asList(mStudentList));
}
You can manipulate livedata using livedata transformations.
val transformedLiveData = Transformations.map(
yourActualLiveData) { //Shuffle logic here }
Well if you are interested in Kotlin solution you could do it like this:
val mStudentList = MutableLiveData<List<StudentEntity>>()
fun setRandomOrder() {
mStudentList.value?.let { students ->
mStudentList.value = students.shuffled()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.