
com.github.davidmoten.rx.Checked Maven / Gradle / Ivy
package com.github.davidmoten.rx;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Action2;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
/**
* Utility functions that are useful for brevity when using checked exceptions
* in lambdas with RxJava.
*
*
* Instead of
*
*
*
* OutputStream os = ...;
* Observable<String> source = ...;
* source.doOnNext(s -> {
* try {
* os.write(s.getBytes());
* } catch (IOException e) {
* throw new RuntimeException(e);
* }
* })
* .subscribe();
*
*
*
* you can write:
*
*
*
* source.doOnNext(Checked.a1(s -> os.write(s.getBytes()))).subscribe();
*
*/
public final class Checked {
public static interface F0 {
T call() throws Exception;
}
public static interface F1 {
R call(T t) throws Exception;
}
public static interface F2 {
S call(T t, R r) throws Exception;
}
public static interface A0 {
void call() throws Exception;
}
public static interface A1 {
void call(T t) throws Exception;
}
public static interface A2 {
void call(T t, R r) throws Exception;
}
/**
* Returns a {@link Func0} that reports any exception thrown by f wrapped by
* a {@link RuntimeException}.
*
* @param f
* has same signature as Func0 but can throw an exception
* @param
* type parameter
* @return a {@link Func0} that reports any exception thrown by f wrapped by
* a {@link RuntimeException}.
*
*/
public static Func0 f0(final F0 f) {
return new Func0() {
@Override
public T call() {
try {
return f.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
public static Func1 f1(final F1 f) {
return new Func1() {
@Override
public R call(T t) {
try {
return f.call(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
public static Func2 f2(final F2 f) {
return new Func2() {
@Override
public S call(T t, R r) {
try {
return f.call(t, r);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
public static Action0 a0(final A0 a) {
return new Action0() {
@Override
public void call() {
try {
a.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
public static Action1 a1(final A1 a) {
return new Action1() {
@Override
public void call(T t) {
try {
a.call(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
public static Action2 a2(final A2 a) {
return new Action2() {
@Override
public void call(T t, R r) {
try {
a.call(t, r);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy