问题描述
我想知道是否有人可以阐明这个问题,何时使用
I wondered if someone can shed some light on this question, when to use
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>
*/
推荐答案
在您提到的用例中,实际上没有重大区别.
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)
}
然后,带有Single.just(getTimeObject())
的结果Single
在具有新订户时将发出相同的Long
.
Then with, Single.just(getTimeObject())
the resulting Single
will emit the same Long
when it has a new subscriber.
但是,使用Single.fromcallable(()-> getTimeObject())
时,得到的Single
将发出不同的Long
,以指示新用户具有当前时间(以毫秒为单位).
However, with Single.fromcallable(()-> getTimeObject())
, the resulting Single
will emit a different Long
indicating the current time in millis when it has a new subscriber.
这是因为fromCallable
每当有新订阅者懒惰时都会执行lambda.
That's because fromCallable
executes it's lambda everytime it has a new subscriber Lazily.
这篇关于RxJava Single.just()与Single.fromCallable()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!