co.easimart.vertx.stream.CancellableReadStream Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of vertx-util Show documentation
Show all versions of vertx-util Show documentation
Library provides utility classes for Vertx project development.
The newest version!
package co.easimart.vertx.stream;
import io.vertx.core.Handler;
import io.vertx.core.streams.ReadStream;
/**
* ReadStream<T> which can be cancelled in the middle.
* exceptionHandler will be called when it is cancelled.
* If the stream has ended already, nothing happens.
*/
public class CancellableReadStream implements ReadStream {
private Handler endHandler;
private Handler exceptionHandler;
private final ReadStream stream;
private boolean ended;
public CancellableReadStream(ReadStream stream) {
this.stream = stream;
this.ended = false;
this.stream.exceptionHandler(throwable -> {
if (this.exceptionHandler != null) this.exceptionHandler.handle(throwable);
});
this.stream.endHandler(r -> {
this.ended = true;
if (this.endHandler != null) this.endHandler.handle(r);
});
}
@Override
public ReadStream exceptionHandler(Handler handler) {
this.exceptionHandler = handler;
return this;
}
public void cancel(Throwable t) {
if (this.ended) return;
if (this.exceptionHandler != null) {
this.exceptionHandler.handle(t);
} else {
this.stream.pause();
this.endHandler.handle(null);
}
}
@Override
public ReadStream handler(Handler handler) {
this.stream.handler(handler);
return this;
}
@Override
public ReadStream pause() {
this.stream.pause();
return this;
}
@Override
public ReadStream resume() {
this.stream.resume();
return this;
}
@Override
public ReadStream endHandler(Handler handler) {
this.endHandler = handler;
return this;
}
}