RxSwift缓冲区性能

时间:2018-07-24 16:29:55

标签: swift rx-swift

是否存在buffer形式的计时器无法连续轮询?因此,性能确实会受到打击。理想情况下,buffer将在产生值之前等待 n 秒,然后在接收到新事件之前不设置新计时器。

1 个答案:

答案 0 :(得分:0)

这是我对非轮询缓冲区的尝试:

extension Observable {

    private struct Buffered<T> {
        let lastFlush: Date
        let remaining: RxTimeInterval
        let value: [T]
    }

    func buffered(delay: RxTimeInterval) -> Observable<[Element]> { return
        scan(
            Buffered<Element>(
                lastFlush: Date(),
                remaining: delay,
                value: []
            )
        ) { sum, x in
            let latest = Date()
            let isExpired = latest > (sum.lastFlush + delay)
            let adjusted = isExpired ? latest : sum.lastFlush
            return Buffered<Element>(
                lastFlush: adjusted,
                remaining: isExpired
                           ? delay
                           : delay - latest.timeIntervalSince(adjusted)
                ,
                value: isExpired ? [x] : sum.value + [x]
            )
        }
        .flatMapLatest {
            Observable
                .just($0.value)
                .delay(
                    $0.remaining,
                    scheduler: MainScheduler.instance
                )
                //.ignoringCompletions()
        }
    }

    public func ignoringCompletions() -> Observable { return
         concat(Observable.never())
    }
}