I'm having a hard time understanding some component in RxJava and how they work. I have these code based on how to implement Repository Pattern with RxJava:
private Observable<String> getData(boolean refresh) {
Observable<String> a = Observable.concat(getCache(), getNetwork());
if(!refresh) {
a.first(s -> s.equals("cache"));
}
return a;
}
private Observable<String> getCache() {
return Observable.just("cache");
}
private Observable<String> getNetwork() {
return Observable.just("network");
}
And I called the function:
getData(false).subscribe(s -> Log.d("Not Refresh", s));
getData(true).subscribe(s -> Log.d("Refresh", s));
// Both of them print this:
// cache
// network
Which doesn't right because I applied first()
function when refresh = true
.
Then, I thought maybe first()
operator didn't reflect to the original object; so I re-assign it back.
if(!refresh) {
a = a.first(s -> s.equals("cache"));
}
Then it worked like I wanted to and print these lines:
// Not Refresh cache
// Refresh cache
// Refresh network
I moved on and learn on another thing, RxBus. My code:
private ReplaySubject<Object> subject = ReplaySubject.create();
private <T> Observable<T> subscribe(Class<T> desiredClass) {
return subject
.filter(item -> item.getClass().equals(desiredClass)) // Note this line
.map(item -> (T) item);
}
private <T> void post(T item) {
subject.onNext(item); // This one too
}
Called the functions with these:
sub(String.class).subscribe(s -> Log.d("Sub String", s));
sub(Integer.class).subscribe(s -> Log.d("Sub Integer", s + ""));
post("String A");
post(5);
// Result:
// Sub String A
// Sub Integer 5
When I call sub()
, it applied filter()
and map()
operators and return it. In my understanding the original subject is not changed, then why does invoking subject.onNext()
also invoke the modified object returned in the sub()
?
Does it have anything to do with Subject? Or my understanding of RxJava is completely wrong here?