Firstly, thank you everyone for spending time helping me. I am not sure whether what I write the bellow code is correct or not. So if you do see any problem please let me know and maybe suggest some way to solve it.
So I want to apply rxjava in my 2 classes to present the observer and observable. So that whenever the currentPage in observable change by clicking a button in JavaFX, the observer will be notify and update. Despite the code run fine, I am not sure creating an observable variable every time is right or not? And also is the onComplete will un-subscribe or do some cleaning or not (I suspect that my code can have some leak memory). Since I cannot find any online resource that have a clear summarize/ explanation about this, I really need help from you guys. Thank you!
P/s: I am new to RxJava so please don't be harsh on me. Thank you!
So the PrimaryInfoModel is the observer:
public class PrimaryInfoModel {
private int currentPage;
private int currentCategory;
public static Observer<Integer> getPageObserver() {
return new Observer<>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
System.out.println("onSubscribe");
}
@Override
public void onNext(@NonNull Integer integer) {
System.out.println(integer); currentPage = integer;
}
@Override
public void onError(@NonNull Throwable e) {
System.out.println(e.getMessage());
}
@Override
public void onComplete() {
System.out.println("Complete");
}
};
}
}
And the NavigationController is the obserable:
public class NavigationController implements Initializable {
private int currentPage;
private Observable<Integer> observable;
public NavigationController() {
}
@FXML
private Button page1, page2, page3, page4, page5, prevPage, nextPage;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
setCurrentButton();
}
@FXML
private void setCurrentButton(MouseEvent event) {
int oldPage = currentPage;
cleanEffect();
Object source = event.getSource();
if (source == page1) {
currentPage = 0;
}
if (source == page2) {
currentPage = 1;
}
if (source == page3) {
currentPage = 2;
}
if (source == page4) {
currentPage = 3;
}
if (source == page5) {
currentPage = 4;
}
if (oldPage != currentPage) {
observable = getObservable();
observable.observeOn(Schedulers.io()).subscribeOn(Schedulers.io()).subscribe(PrimaryInfoModel.getPageObserver());
}
}
private Observable<Integer> getObservable() {
return Observable.create(new ObservableOnSubscribe<Integer>() {
@Override
public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable {
emitter.onNext(currentPage);
emitter.onComplete();
}
});
}
}