首页 > 解决方案 > 如何观察属性在 RxSwift 中的特定时间间隔内是否没有变化

问题描述

我想观察speedCLLocation 更新的属性,如果速度在 10 秒内没有变化并且速度变化会重置计时器,则触发一个事件。到现在也只能想出这么多代码。

let location: Observable<CLLocation>

location.subscribe(onNext: { (coordinates) in
    print(coordinates)
})
.disposed(by: disposeBag)

我认为我们可以使用debouncethrottle不确定如何使用。

标签: iosswiftcore-locationrx-swift

解决方案


试试这个:

// will emit element when speed doesn't change for 10 seconds
let lastLocation = location
    .distinctUntilChanged { $0.speed == $1.speed }
    .debounce(.seconds(10), scheduler: MainScheduler.instance) 

Observable.merge(location, lastLocation)
    .subscribe(onNext: { coordinates in
        print(coordinates)
    })
    .disposed(by: disposeBag)

推荐阅读