![](/img/trans.png)
[英]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.