如何解决如何从和到LiveData<List<Object>> 添加和删除 <Object>?
我有一个 recyclerView,里面装满了 LiveData currentList。
我使用 Single
并在 onSuccess 方法中使用 currentList.setValue(people) 添加人员(请参阅下面的代码)。
但是当我打开应用程序时,recyclerView 中只有 1 个对象。
我的任务是:
1) 当应用程序打开时,它必须将 4 人添加到 recyclerView(即到 currentList);
2) 在 onSwipe 方法之后,它必须删除第一个并将 RoomDatabase 中的 1 个新随机添加到 currentList 的末尾。
这意味着我需要删除和添加对象到 LiveData 的方法。
我怎样才能做到这一点? (ViewModel 代码如下)
public class PersonViewModel extends AndroidViewModel {
private PersonRepository mRepository;
private CompositeDisposable composite = new CompositeDisposable();
private Single<List<Person>> mGuyWho; // это нада??? LOBNYA
private Single<Person> mGuy; // PSKOV
private MutableLiveData<List<Person>> currentList = new MutableLiveData<>();
public PersonViewModel(@NonNull Application application) {
super(application);
mRepository = new PersonRepository(application);
mGuyWho = mRepository.getGuyWho(); //это нада?? LOBNYA
mGuy = mRepository.getGuy(); // PSKOV
mGuyWho.subscribeOn(Schedulers.io()) // LOBNYA nachalo
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<List<Person>>() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG,"onSubscribe(Disposable d): called");
composite.add(d);
}
@Override
public void onSuccess(List<Person> people) {
Log.d(TAG,"onSuccess: called");
currentList.setValue(people); // here I pass List to LiveData<List>
}
@Override
public void onError(Throwable e) {
Log.d(TAG,"onError: called");
Toast.makeText(application,"NO DATA",Toast.LENGTH_SHORT).show();
}
}); // LOBNYA konets
mGuy.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Person>() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG,"onSubscribe(Disposable d): called");
composite.add(d);
}
@Override
public void onSuccess(Person person) {
Log.d(TAG,"onSuccess: called");
currentList.setValue(person); // there is an error,for I cannot bypass <Person> to LiveData<List<>>
}
@Override
public void onError(Throwable e) {
Log.d(TAG,"onError: called");
}
})
}
LiveData<List<Person>> getCurrentList() {
return currentList;
}
};
解决方法
您的 LiveData
由一个 List<Person>
对象组成:
private MutableLiveData<List<Person>> currentList = new MutableLiveData<>();
在您的 onSuccess()
方法中,您试图将一个 Person
对象传递给它。您应该在那里传递 mutableListOf(Person())
以使其工作。 但是,这仍然不能解决您的问题。
您需要做的是:
- 接收 ViewHolder 的
onSwipe
事件并在您的remove
中调用viewModel
方法。 - 此
remove
方法应通过删除元素来修改您的currentList
。您可以将id
传递给remove
方法以简化操作。 - 因为
currentList
是LiveData
每observer
都会收到通知。 - 然后您需要从
Room Database
中获取随机条目。 - 将此随机条目添加到
currentList
。为此,您可以使用Transformations
的LiveData
API。 - 再说一次,因为
currentList
是LiveData
,所以每个Observer
都会收到通知。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。