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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52670628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:33:50  来源:igfitidea点击:

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

javaandroidrx-java2

提问by bastami82

I wondered if someone can shed some light on this question, when to use

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

Single.fromCallable( ()-> myObject )

instead of

代替

Single.just(myObject)


from the documentation, Single.fromCallable():

从文档中,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.
 */

and the documentation for Single.just():

和文档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>
 */

采纳答案by Ahmed Ashraf

In the use case you've mentioned, there is actually no major difference.

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

Now imagine we need the object to be created dynamically through a function call?

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

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

Then with, Single.just(getTimeObject())the resulting Singlewill emit the same Longwhen it has a new subscriber.

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

However, with Single.fromcallable(()-> getTimeObject()), the resulting Singlewill emit a different Longindicating the current time in millis when it has a new subscriber.

然而,当它有一个新订阅者时Single.fromcallable(()-> getTimeObject()),结果Single将发出一个不同的Long指示以毫秒为单位的当前时间。

That's because fromCallableexecutes it's lambda everytime it has a new subscriber Lazily.

那是因为fromCallable每当它有一个新订阅者Lazily 时,它就会执行它的 lambda 。

回答by DenZap

You should use fromCallable()when you have a function like

当你有一个类似的函数时,你应该使用fromCallable()

MyObject myFunction() {
    // some login here
    return new MyObject();
}

Then you can create Singlefrom this function like this:

然后你可以像这样从这个函数创建Single

Single.fromCallable(() -> myFunction());

Single.just(myObject)just emits your object without any logic.

Single.just(myObject)只是在没有任何逻辑的情况下发出您的对象。

So there is no need to use fromCallable()when you want to emit specific item.

因此,当您想要发出特定项目时,无需使用fromCallable()

回答by laalto

Usually you will notice the difference when the thing you're emitting is not just an object but actually a result of some method calls that involve either heavy computation, I/O, or state.

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

Single.just(x)evaluates the ximmediately in the current thread and then you're left with whatever was the result of x, for all subscribers.

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

Single.fromCallable(y)invokes the ycallable in the subscribeOnscheduler at the time of subscription and separately for each subscriber.

Single.fromCallable(y)ysubscribeOn订阅时为每个订阅者分别调用调度程序中的可调用对象。



So for example, if you wanted to offload an I/O operation to a background thread, you'd use

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

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

Having Single.just()here would not work since someIoOperation()would be executed on the current thread.

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

回答by aya salama

In the documents they distinguished between two times Assemble timeand Runtime;

在文档中,他们区分了两次Assemble timeRuntime

Assembly timeThe preparation of dataflows by applying various intermediate operators

RuntimeThis is the state when the flows are actively emitting items

组装时间通过应用各种中间操作符来准备数据流

运行时这是流主动发出项目时的状态

Simply Single.just()is evaluated in the Assembly timenot after the main process is completed

简单的Single.just()组装时间而不是在主进程完成后进行评估

Single.defer() and Single.fromcallable()evaluate the Single object in Runtime

Single.defer() 和 Single.fromcallable()运行时评估 Single 对象

Please check official documents code examples here

在此处查看官方文档代码示例