你需要让你的模型可以观察到变化。
public class User {
public interface ChangeListener {
void onChanged(User user);
}
private List<ChangeListener> changeListeners = new CopyOnWriteArrayList<>();
public void addChangeListener(ChangeListener listener) {
this.changeListeners.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
this.changeListeners.remove(listener);
}
private String firstName;
private String lastName;
public void setFirstName(String firstName) {
this.firstName = firstName;
for(ChangeListener changeListener: changeListeners) {
changeListener.onChanged(this);
}
}
}
因为现在你可以观察一个用户:
user.addChangeListener((u) -> {
// user changed
});
现在你可以很容易地把它包装成可观察的:
public class RxUser {
private RxUser() {}
public static Observable<User> observe(final User user) {
return Observable.create((emitter) -> {
final User.ChangeListener changeListener = (user) -> {
emitter.onNext(user);
}
emitter.setDisposable(Disposables.fromAction(() -> { user.removeChangeListener(listener); }));
user.addChangeListener(listener);
});
}
现在你可以做了
User u = new User();
Disposable disposable = RxUser.observe(u).subscribe((user) -> {
// will be called for changes
});
u.setFirstName("hello");