Skip to content

Instantly share code, notes, and snippets.

@abersnaze
Last active April 29, 2016 20:23
Show Gist options
  • Save abersnaze/9507aaa12e944154a9641af3086cd900 to your computer and use it in GitHub Desktop.
Save abersnaze/9507aaa12e944154a9641af3086cd900 to your computer and use it in GitHub Desktop.
A Session Manager Class.
import java.util.function.Function;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
public class Session<T> {
public static interface CheckedFunc0<R> {
public R call() throws Exception;
}
public static interface CheckedAction1<T> {
public void call(T t) throws Exception;
}
private CheckedFunc0<T> resourceFactory;
private CheckedAction1<? super T> disposeAction;
public Session(final CheckedFunc0<T> resourceFactory, final CheckedAction1<? super T> disposeAction) {
this.resourceFactory = resourceFactory;
this.disposeAction = disposeAction;
}
public final Completable checkoutWriteOnly(final Function<? super T, Completable> func) {
return checkoutReadWrite(t -> func.apply(t).toObservable()).toCompletable();
}
public final <R> Observable<R> checkoutReadWrite(final Func1<? super T, ? extends Observable<? extends R>> func) {
return Observable.using(() -> {
try {
return resourceFactory.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
} , func, (rsrc) -> {
try {
disposeAction.call(rsrc);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
}
@Psarmmiey
Copy link

If I may ask, Where do one get the "rx" Package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment