如何使可观察间隔立即开始而不延迟?
How do I make an Observable Interval start immediately without a delay?
我希望我的 Observable 立即触发,并且每秒触发一次。 interval
will not fire immediately. I found this question 建议使用 startWith
,它会立即触发,但我会得到重复的第一个条目。
Rx.Observable.interval(1000).take(4).startWith(0).subscribe(onNext);
https://plnkr.co/edit/Cl5DQ7znJRDe0VTv0Ux5?p=preview
如何立即进行间隔触发,而不是复制第一个条目?
在 RxJs 6 之前:
Observable.timer(0, 1000)
将立即开始。
RxJs 6+
import {timer} from 'rxjs/observable/timer';
timer(0, 1000).subscribe(() => { ... });
使用 RxJava2,重复第一个条目没有问题,这段代码工作正常:
io.reactivex.Observable.interval(1, TimeUnit.SECONDS)
.startWith(0L)
.subscribe(aLong -> {
Log.d(TAG, "test"); // do whatever you want
});
注意你需要在startWith中传递Long
,所以0L
。
RxJs 6. Note: With this solution, 0
value will be emitted twice (one time immediately by startWith
, and one time by interval
stream after the first "tick", so if you care about the value emitted, you could consider startWith(-1) instead of startWith(0)
interval(100).pipe(startWith(0)).subscribe(() => { //your code });
或使用定时器:
import {timer} from 'rxjs/observable/timer';
timer(0, 100).subscribe(() => {
});
RxJava 2
如果要生成每个值延迟 D 秒的序列 [0, N]
,请使用以下重载:
Observable<Long> interval(long initialDelay, long period, TimeUnit unit)
initialDelay - the initial delay time to wait before emitting the first value of 0L
Observable.interval(0, D, TimeUnit.SECONDS).take(N+1)
您也可以尝试使用 startWith(0L)
但它会生成如下序列:{0, 0, 1, 2...}
我相信类似的东西也能完成这项工作:
Observable.range(0, N).delayEach(D, TimeUnit.SECONDS)
我希望我的 Observable 立即触发,并且每秒触发一次。 interval
will not fire immediately. I found this question 建议使用 startWith
,它会立即触发,但我会得到重复的第一个条目。
Rx.Observable.interval(1000).take(4).startWith(0).subscribe(onNext);
https://plnkr.co/edit/Cl5DQ7znJRDe0VTv0Ux5?p=preview
如何立即进行间隔触发,而不是复制第一个条目?
在 RxJs 6 之前:
Observable.timer(0, 1000)
将立即开始。
RxJs 6+
import {timer} from 'rxjs/observable/timer';
timer(0, 1000).subscribe(() => { ... });
使用 RxJava2,重复第一个条目没有问题,这段代码工作正常:
io.reactivex.Observable.interval(1, TimeUnit.SECONDS)
.startWith(0L)
.subscribe(aLong -> {
Log.d(TAG, "test"); // do whatever you want
});
注意你需要在startWith中传递Long
,所以0L
。
RxJs 6. Note: With this solution,
0
value will be emitted twice (one time immediately bystartWith
, and one time byinterval
stream after the first "tick", so if you care about the value emitted, you could consider startWith(-1) instead of startWith(0)
interval(100).pipe(startWith(0)).subscribe(() => { //your code });
或使用定时器:
import {timer} from 'rxjs/observable/timer';
timer(0, 100).subscribe(() => {
});
RxJava 2
如果要生成每个值延迟 D 秒的序列 [0, N]
,请使用以下重载:
Observable<Long> interval(long initialDelay, long period, TimeUnit unit)
initialDelay - the initial delay time to wait before emitting the first value of 0L
Observable.interval(0, D, TimeUnit.SECONDS).take(N+1)
您也可以尝试使用 startWith(0L)
但它会生成如下序列:{0, 0, 1, 2...}
我相信类似的东西也能完成这项工作:
Observable.range(0, N).delayEach(D, TimeUnit.SECONDS)