当我创建带有Observable
的lambda的Runnable
时,代码将按计划执行run
方法。但是,如果我创建一个新的Runnable,则代码不会执行该计划,则什么都不会发生?
获取和使用Runnable
Observable<Usage> usageObservable = Observable.create(emitter -> {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(createNewUsageListener(emitter), 0, 2, TimeUnit.SECONDS);
});
ConnectableObservable<Usage> connectableObservable = usageObservable.share().publish();
connectableObservable.connect();
按ScheduledExecutorService
时间表工作和执行的代码。
private Runnable createNewUsageListener(ObservableEmitter<Usage> emitter) {
return () -> {
List<Usage> usages = getUpdates(rollDice(0, 5));
if (usages != null) {
emitUsageStats(emitter, usages);
}
};
}
此代码对我来说似乎是相同的代码,但是不会在ScheduledExecutorService
private Runnable createNewUsageListener(ObservableEmitter<Usage> emitter) {
return new Runnable() {
@Override
public void run() {
List<Usage> usages = getUpdates(rollDice(0, 5));
if (usages != null) {
emitUsageStats(emitter, usages);
}
}
};
}