gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:56:31 28 4
gpt4 key购买 nike

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

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

最佳答案

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

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

Single.fromCallable(y) 在订阅时分别为每个订阅者调用 subscribeOn 调度器中的 y 可调用函数。


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

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

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

关于java - RxJava Single.just() vs Single.fromCallable()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52670628/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com