实际上没有什么区别。以下是代码:
public final class CompletableFromAction extends Completable {
final Action run;
public CompletableFromAction(Action run) {
this.run = run;
}
@Override
protected void subscribeActual(CompletableObserver observer) {
Disposable d = Disposables.empty();
observer.onSubscribe(d);
try {
run.run();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
if (!d.isDisposed()) {
observer.onError(e);
} else {
RxJavaPlugins.onError(e);
}
return;
}
if (!d.isDisposed()) {
observer.onComplete();
}
}
}
public final class CompletableFromCallable extends Completable {
final Callable<?> callable;
public CompletableFromCallable(Callable<?> callable) {
this.callable = callable;
}
@Override
protected void subscribeActual(CompletableObserver observer) {
Disposable d = Disposables.empty();
observer.onSubscribe(d);
try {
callable.call();
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
if (!d.isDisposed()) {
observer.onError(e);
} else {
RxJavaPlugins.onError(e);
}
return;
}
if (!d.isDisposed()) {
observer.onComplete();
}
}
}
Callable
想要包装在一个Completable
中,可以直接使用它。如果你有一个Action
或Runnable
,也是一样(Completable.fromRunnable
也是如此)。如果只存在一个,你需要做一些额外的工作来转换成另一个。对我来说,唯一的区别是当你深入研究Action0与Callable的实际差异时,这两者的工作方式不同:
public interface Action0 extends Action {
void call();
}
vs
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
基本上,如果你的逻辑返回了空值(这正是Callable的情况),你最好选择Completable.fromAction
来使代码更加简洁。