RxJava Single.just() vs Single.fromCallable()?

2022-09-01 04:45:39

我想知道是否有人可以对这个问题有所了解,何时使用

Single.fromCallable( ()-> myObject )

而不是

Single.just(myObject)

从文档中, :Single.fromCallable()

 /**
 * Returns a {@link Single} that invokes passed function and emits its result for each new SingleObserver that subscribes.
 * <p>
 * Allows you to defer execution of passed function until SingleObserver subscribes to the {@link Single}.
 * It makes passed function "lazy".
 * Result of the function invocation will be emitted by the {@link Single}.
 * <dl>
 *   <dt><b>Scheduler:</b></dt>
 *   <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd>
 * </dl>
 *
 * @param callable
 *         function which execution should be deferred, it will be invoked when SingleObserver will subscribe to the {@link Single}.
 * @param <T>
 *         the type of the item emitted by the {@link Single}.
 * @return a {@link Single} whose {@link SingleObserver}s' subscriptions trigger an invocation of the given function.
 */

和以下各项的文档:Single.just()

 /**
 * Returns a {@code Single} that emits a specified item.
 * <p>
 * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.just.png" alt="">
 * <p>
 * To convert any object into a {@code Single} that emits that object, pass that object into the
 * {@code just} method.
 * <dl>
 * <dt><b>Scheduler:</b></dt>
 * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd>
 * </dl>
 *
 * @param item
 *            the item to emit
 * @param <T>
 *            the type of that item
 * @return a {@code Single} that emits {@code item}
 * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a>
 */

答案 1

通常,当您发出的东西不仅仅是一个对象,而是实际上涉及大量计算,I / O或状态的某些方法调用的结果时,您会注意到差异。

Single.just(x)立即在当前线程中评估,然后您就只剩下 所有订阅者的结果。.xx

Single.fromCallable(y)在订阅时在计划程序中调用可调用对象,并为每个订阅者单独调用。ysubscribeOn


例如,如果要将 I/O 操作卸载到后台线程,则可以使用

Single.fromCallable(() -> someIoOperation()).
    subscribeOn(Schedulers.io()).
    observeOn(AndroidSchedulers.mainThread()).
    subscribe(value -> updateUi(value), error -> handleError(error));

在这里不起作用,因为将在当前线程上执行。Single.just()someIoOperation()


答案 2

在你提到的用例中,实际上没有重大区别。

现在想象一下,我们需要通过函数调用动态创建对象吗?

fun getTimeObject() {
    val timeInMillis = System.currentTimeMillis()
    return TimeObject(timeInMillis)
}

然后,当它有一个新的订阅者时,结果将发出相同的结果。Single.just(getTimeObject())SingleLong

但是,使用 ,当它有新的订阅者时,结果将发出不同的指示,以毫为单位的当前时间。Single.fromcallable(()-> getTimeObject())SingleLong

这是因为每次它有一个新的订阅者懒惰地执行它的lambda。fromCallable


推荐