我想知道是否有人可以阐明这个问题,何时使用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> */
3 回答
慕标琳琳
TA贡献1830条经验 获得超9个赞
在您提到的用例中,实际上没有重大区别。
现在想象一下我们需要通过函数调用动态创建对象吗?
fun getTimeObject() {
val timeInMillis = System.currentTimeMillis()
return TimeObject(timeInMillis)
}
然后,当它有一个新订阅者时,Single.just(getTimeObject())结果Single将发出相同的信息Long。
然而,当它有一个新订阅者时Single.fromcallable(()-> getTimeObject()),结果Single将发出一个不同的Long指示以毫秒为单位的当前时间。
那是因为fromCallable每当它有一个新订阅者Lazily 时,它就会执行它的 lambda 。
青春有我
TA贡献1784条经验 获得超8个赞
当你有一个类似的函数时,你应该使用fromCallable()
MyObject myFunction() {
// some login here
return new MyObject();
}
然后你可以像这样从这个函数创建Single:
Single.fromCallable(() -> myFunction());
Single.just(myObject)只是在没有任何逻辑的情况下发出您的对象。
因此,当您想要发出特定项目时,无需使用fromCallable()。
添加回答
举报
0/150
提交
取消