The answer from @ctietze seems right. But after make a test, I realize that throttle
kills the whole concept.
Basically throttle
will return the value right after the observable start. That mean it won't wait until 0.4s
to emit the first value.
func testWithThrottle() -> Observable<Int> {
return
Observable.just(7) // 1
.concat(Observable.never()) // 2
.throttle(3.0, scheduler: Schedulers.background) // 3
.take(1) // 4
// 1. -7--|->
// 2. -7------------------------------->
// 3. -7------------------------------->
// 4. -7--|->
}
...
print("[\(Date())] Start!")
testWithThrottle().subscribe({ (event) in
print("[\(Date())] event: \(event)")
}).addDisposableTo(disposeBag)
print("[\(Date())] End!")
...
[2017-06-03 03:14:00 +0000] Start!
[2017-06-03 03:14:00 +0000] event: next(7)
[2017-06-03 03:14:00 +0000] event: completed
[2017-06-03 03:14:00 +0000] End!
SO, what is the solution? Easy, you need to use debounce
instead.
func testWithDebounce() -> Observable<String> {
return
Observable.of("A") // 1
.concat(Observable.never()) // 2
.debounce(3.0, scheduler: Schedulers.background) // 3
.take(1) // 4
// 1. -A-|->
// 2. -A------------------------------>
// 3. ---------------A---------------->
// 4. ---------------A-|->
}
...
[2017-06-03 03:24:21 +0000] Start Thrrotle!
[2017-06-03 03:24:21 +0000] Finish Thrrotle!
[2017-06-03 03:24:24 +0000] event: next(A)
[2017-06-03 03:24:24 +0000] event: completed