Are RxJava Items Needed?
I just started learning RxJava and was thinking about reactivity. I found an article (7 Tips) that says that items should only be used as a last resort or first implementation, and I thought ... At the moment I have one PublishSubject
PublishSubject.create()
.scan(0, (a, b) -> a + 1).subscribe(replaySubject)
It increments the value by 1 each time and is signed by the replaySubject function
ReplaySubject.create ();
It just prints out the value. So on startup I have 0, then on each PublishSubject.onNext
I increment the value, so I got 1, 2, etc. Since its replaySubject I am getting the whole chain. However, I was wondering if this could be done without items? I've read the RxJava Wiki and Operators, but I can't figure out how this can be done.
Update
So the pseudocode I'm trying to archive somehow has one observable that starts at 1
Observable.just(1)
Now I have on my click listener
OnClick{ }
And every time I click on some button, I want to see all the previous numbers + 1, so 1, then 1, then 2, the next 1,2,3, etc. I tried with ConnectableObservator.replay
but it failed. And inside the listener, I tried to first add a scan on my Observable to increment the value and then subscribe so that I can print it. But that doesn't work either. Hell, I think I'm in a black corner and misunderstood the idea of observables ...
source to share
Since you are writing an Android application, you can use RxAndroid. Here's an example,
Observable.just(1).flatMap(new Func1<Integer, Observable<Integer>>() {
@Override
public Observable<Integer> call(Integer initialValue) {
return ViewObservable.clicks(button, false)
.subscribeOn(AndroidSchedulers.mainThread())
.scan(initialValue, new Func2<Integer, View, Integer>() {
@Override
public Integer call(Integer integer, View v) {
return integer + 1;
}
});
}
}).subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(Integer integer) {
System.out.println(integer);
}
});
I'm not sure if this is what you want. Perhaps you only need:
ViewObservable.clicks(button, false)
.subscribeOn(AndroidSchedulers.mainThread())
.scan(1, new Func2<Integer, View, Integer>() {
@Override
public Integer call(Integer integer, View v) {
return integer + 1;
}
}).subscribe(new Observer<Integer>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(Integer integer) {
System.out.println(integer);
}
});
source to share