[英]How to delete object from list in JSON using SpringBoot and MongoDB
[英]how to add and delete <Object> from (and to) LiveData<List<Object>>?
我有一个用 LiveData<List> currentList 填充的 recyclerView。 我采用 Single<List> 并在 onSuccess 方法中使用 currentList.setValue(people) 添加人员(请参见下面的代码)。 但是当我打开应用程序时,recyclerView 中只有 1 个 object。 我的任务是: 1)当应用程序打开时,它必须将 4 人添加到 recyclerView(即 currentList); 2) 在 onSwipe 方法之后,它必须删除第一个并将 RoomDatabase 中的 1 个新随机添加到 currentList 的末尾。
这意味着我需要将对象删除和添加到 LiveData<List> 的方法。 我怎样才能做到这一点? (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>
object 组成:
private MutableLiveData<List<Person>> currentList = new MutableLiveData<>();
在您的onSuccess()
方法中,您尝试将Person
object 传递给它。 您应该在其中传递mutableListOf(Person())
以使其正常工作。 但是,这仍然不能解决您的问题。
您需要执行以下操作:
onSwipe
事件并在viewModel
中调用remove
方法。remove
方法应通过删除元素来修改您的currentList
。 您可以将id
传递给remove
方法以使事情变得更容易。currentList
是LiveData
每个observer
都会收到通知。Room Database
中获取随机条目。currentList
。 您可以为此使用 LiveData 的Transformations
LiveData
。currentList
是LiveData
,每个Observer
都会收到通知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.