我目前正在使用MVVM和RxJava 2开发一个小示例应用程序。
您可以在下面的代码中看到,我使用一个Observable将数据从模型流传输到视图(活动),但是在更新数据时,观察者(活动)从未收到有关更新的通知。只有在第一次检索数据时,才会通知观察者。
/**
* This will simulate a data repository that could retrieve data
* from local or network providers in an actual implementation.
* <p>
* This repository is only implemented as Singleton for simulation reasons.
*/
public class NamePairRepository {
private static final String[] firstNames = {"Kathrin", "Carl", "Denise", "Albert", "Melanie", "Tom"};
private static final String[] lastNames = {"Smith", "Jordan", "Sarkozy", "McDonald", "Pillepalle", "Bacon"};
private static NamePairRepository instance = null;
public static NamePairRepository getInstance() {
if (instance == null) {
instance = new NamePairRepository();
}
return instance;
}
private NamePair namePair;
private Random random = new Random();
private NamePairRepository() {
namePair = new NamePair(firstNames[0], lastNames[0]);
}
public Observable<NamePair> getNamePair() {
return Observable.just(namePair);
}
public void updateFirstName() {
new Handler().postDelayed(() ->
namePair.setFirstName(firstNames[random.nextInt(firstNames.length)]),
1000);
}
public void updateLastName() {
new Handler().postDelayed(() ->
namePair.setLastName(lastNames[random.nextInt(lastNames.length)]),
1000);
}
}
@Override
protected void onResume() {
super.onResume();
compositeDisposable = new CompositeDisposable();
compositeDisposable.add(viewModel.getNamePair()
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::setNames));
}
@Override
protected void onPause() {
super.onPause();
compositeDisposable.clear();
}
不幸的是,我是RxJava的新手,但据我了解,观察者模式,可观察对象应始终将更改通知给观察者,对吧?
请随时结帐该项目:https://github.com/CodeRedDev/Android-Architecture/tree/mvvm