我想知道是否有人可以阐明这个问题,何时使用
#! /bin/bash
useradd -G sudo USERNAME
echo 'USERNAME:PASSWORD' | chpasswd
代替
Single.fromcallable(()-> myObject)
来自文档Single.formcallable
Single.Just(myObject)
和Single.just文件
/**
* 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.
*/
答案 0 :(得分:18)
通常,当您发出的东西不仅是对象,而且实际上是涉及大量计算,I / O或状态的某些方法调用的结果时,您会注意到差异。
Single.just(x)
在当前线程中立即评估x
,然后为所有订阅者保留x
的结果。
Single.fromCallable(y)
在订阅时调用y
调度程序中的subscribeOn
可调用,并分别为每个订阅者调用。
例如,如果您想将I / O操作卸载到后台线程,则可以使用
Single.fromCallable(() -> someIoOperation()).
subscribeOn(Schedulers.io()).
observeOn(AndroidSchedulers.mainThread()).
subscribe(value -> updateUi(value), error -> handleError(error));
在此处拥有Single.just()
无效,因为someIoOperation()
将在当前线程上执行。
答案 1 :(得分:11)
在您提到的用例中,实际上没有什么大不同。
如果我们需要通过函数调用动态创建对象怎么办?
fun getTimeObject() {
val timeInMillis = System.currentTimeMillis()
return TimeObject(timeInMillis)
}
然后,Single.just(getTimeObject())
与结果Single
拥有一个新订户时将发出相同的Long
。
但是,对于Single.fromcallable(()-> getTimeObject())
,生成的Single
将发出一个不同的Long
,以表示当它有一个新订户时的当前时间(以毫秒为单位)。
这是因为fromCallable
每当有新订阅者懒惰时都会执行lambda。
答案 2 :(得分:1)
当您具有类似
的功能时,应使用 fromCallable()MyObject myFunction() {
// some login here
return new MyObject();
}
然后您可以通过以下函数创建 Single :
Single.fromCallable(() -> myFunction());
Single.just(myObject)仅发出没有任何逻辑的对象。
因此,当您要发出特定项目时,无需使用 fromCallable()。
答案 3 :(得分:0)
在文档中,它们区分了两次组装时间和运行时间;
组装时间 应用各种中间运算符准备数据流
运行时 这是流正在主动发出项目的状态
仅在组装时间中评估 Single.just(),而不是在完成主过程之后
Single.defer()和Single.fromcallable()在运行时
中评估Single对象请检查官方文档代码示例here