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

6.9k views Asked by At

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));
1

There are 1 answers

0
cyroxis On BEST ANSWER

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

Documentation