When should we use Completable.fromAction()
and when should we use Completable.fromCallable()
Is there a specific Usecase
From the documentation it seems that both do the same thing and it is hard to notice the difference between them.
Completable.FromAction
Completable.fromCallable
There really isn't any difference. Here's the code:
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();
}
}
}
So the code is exactly the same. I think they both exist mostly for convenience - if you already have a Callable
you want to wrap in a Completable
, you can just use it directly. Same if you have an Action
, or a Runnable
(Completable.fromRunnable
also exists). If only one existed, you'd have to do a little bit of extra work to convert one to the other.
Sources: https://github.com/ReactiveX/RxJava/blob/2.x/src/main/java/io/reactivex/internal/operators/completable/CompletableFromCallable.java
https://github.com/ReactiveX/RxJava/blob/2.x/src/main/java/io/reactivex/internal/operators/completable/CompletableFromAction.java
Key (and the only) difference for me is when you look into actual difference of Action0 vs Callable those two work with:
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;
}
Basically, if your logic returns nothing (which is exactly the thing in case of Callable), you better go with Completable.fromAction
for cleaner code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With