Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava- performing a peek() or void operation within an Observable chain?

Java 8 lambda streams have a peek() operator which allows you to execute a void operation on each item. This is typically used for debugging, but it also is a nice way to cheat and kick off a void operation without mapping to something.

Is there an equivalent to this in RxJava? Maybe I'm not following a good practice or thinking reactively enough... but it would be really handy to create status labels before and after an operation? If peek() is not supported, is there a better pattern to follow?

Observable<Item> Item= ...;

Label statusLabel = new Label();
Label resultLabel = new Label();

Observable<CalculatedItem> calculatedItem = calculated.subscribeOn(Schedulers.computation())
.peek(c -> statusLabel.setText("Working.."))
.map(c -> performExpensiveCalculation(c))
.peek(r -> statusLabel.setText(""));

calculatedItem.subscribe(c -> resultLabel.setText(c));
like image 277
tmn Avatar asked Jun 10 '15 15:06

tmn


1 Answers

There is a method doOnNext(Action1<Item> action) that will be called for each item in the stream.

Documentation

like image 98
cyroxis Avatar answered Nov 07 '22 22:11

cyroxis