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

新手上路,请多包涵

我想知道是否有人可以阐明这个问题,何时使用

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>
 */

原文由 bastami82 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 486
2 个回答

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

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

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

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

但是,对于 Single.fromcallable(()-> getTimeObject()) ,生成的 Single 将发出不同的 Long 指示当前时间(以毫秒为单位),当它有一个新订阅者时。

那是因为 fromCallable 每次有新订阅者 Lazily 时都会执行它的 lambda。

原文由 Ahmed Ashraf 发布,翻译遵循 CC BY-SA 4.0 许可协议

通常,当您发射的东西不仅是一个对象,而且实际上是一些涉及繁重计算、I/O 或状态的方法调用的结果时,您会注意到不同之处。

Single.just(x) 评估 x 立即在当前线程中,然后您将得到 x 的结果,对于所有订阅者。

Single.fromCallable(y) 调用 y 可在 subscribeOn 调度程序中调用,并在订阅时分别为每个订阅者调用。


因此,例如,如果您想将 I/O 操作卸载到后台线程,您可以使用

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

Single.just() 在这里是行不通的,因为 someIoOperation() 将在当前线程上执行。

原文由 laalto 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题