【发布时间】:2021-01-12 23:48:16
【问题描述】:
我有一个用 LiveData currentList 填充的 recyclerView。
我采用 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;
}
};
【问题讨论】:
标签: java android mvvm rx-java2 android-livedata