我想知道是否有人能解释一下这个问题,什么时候使用?
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>
*/发布于 2018-10-05 18:50:55
在您所提到的用例中,实际上没有重大差别。
现在假设我们需要通过函数调用动态地创建对象吗?
fun getTimeObject() {
val timeInMillis = System.currentTimeMillis()
return TimeObject(timeInMillis)
}然后,使用Single.just(getTimeObject()),生成的Single将在有新订阅服务器时发出相同的Long。
但是,使用Single.fromcallable(()-> getTimeObject()),生成的Single将发出一个不同的Long,指示在millis中有新订阅服务器的当前时间。
这是因为fromCallable执行时,每当它有一个新的订户懒散地使用时,它都是lambda。
发布于 2018-10-05 19:36:37
通常,当您发出的东西不仅是一个对象,而且实际上是一些方法调用的结果时,您会注意到这种差异,这些方法调用涉及大量的计算、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()将在当前线程上执行。
发布于 2018-10-05 18:41:01
当您有这样一个函数时,应该使用fromCallable()
MyObject myFunction() {
// some login here
return new MyObject();
}然后,您可以像这样从这个函数中创建一个:
Single.fromCallable(() -> myFunction());Single.just(myObject)只是在没有任何逻辑的情况下发射你的对象。
因此,当您想要发出特定项时,不需要使用fromCallable()。
https://stackoverflow.com/questions/52670628
复制相似问题