Add auto close for AsyncResultSingle and test
I think this code does not achieve the desired effect and the only way to achieve it is to consider it from the perspective of the Single we return in the generated code. The Single returned by the Rxified API should rather look like:
Single<String> single = Single.just("the-value");
// This will be executed after the single chain is terminated
single = single.doAfterTerminate(() -> {
System.out.println("closing");
});
// Never completes for the sake of the example
single = single.flatMap(v -> Single.never());
single.subscribe(value -> {
System.out.println("success");
}, err -> {
System.out.println("failure");
});
and to have this code, we would need when we generate the code to know that the returned type implements AutoCloseable
So put another way : I don't think we can implement it in AsyncResultSingle in a dynamic manner (with instanceof operator) and we can only use doAfterTerminate on the resulting single at generation time (maybe I'm wrong, and I hope so...)
So first I'm wondering if we can today detect at generation time (in templates) that the type of a single extends AutoCloseable
Since we are closing when the single is disposed, the closing would still happen even if the stream does not terminate.. For example:
AsyncResultSingle<Formatter> single = new AsyncResultSingle<>(h2 -> Future.succeededFuture(new Formatter(new StringBuilder(), Locale.US)).setHandler(h2));
DisposableObserver<Object> obs = new DisposableObserver<Object>() {
@Override
public void onNext(Object formatter) {
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onComplete() {
}
};
single.toObservable().flatMap(v -> Observable.never())
.subscribe(obs);
On executing this program the formatter object is closed properly, inspite of the stream not getting terminated. Please do correct me if I interpreted your comment the wrong way.
I understand this method would work only when the type is known, can you elaborate on how to detect at generation time (in templates) that the type of a single extends AutoCloseable ?
the user case is more for single than streams (although it's not exclusive).
for compile time, the codegen project should support it in ApiTypeInfo with a boolean autoCloseable that says wethers the type has AutoCloseable as super type
Sorry, I'm a bit stuck here: When I add the boolean autoCloseable to ApiTypeInfo and as a constructor parameter, how should I check if the type implements AutoCloseable (Using Reflection perhaps?) in the files TypeReflectionFactory and TypeMirrorFactory which use the constructor?
check at how the same is achieved for the readStream / writeStream booleans