diff --git a/Sources/Verge/Store/StoreDriverType+Accumulator.swift b/Sources/Verge/Store/StoreDriverType+Accumulator.swift index e0bba028c4..6d92fd4a9a 100644 --- a/Sources/Verge/Store/StoreDriverType+Accumulator.swift +++ b/Sources/Verge/Store/StoreDriverType+Accumulator.swift @@ -129,6 +129,9 @@ public struct AccumulationSinkIfChanged: Accumulation private var latestValue: Target? private var previousValue: Target? + private var counter: Int = 0 + private var countToEmit: Int = 0 + private var handler: ((consuming Target) -> Void)? init( @@ -137,6 +140,11 @@ public struct AccumulationSinkIfChanged: Accumulation self.selector = selector } + public consuming func dropFirst(_ k: Int = 1) -> Self { + countToEmit = k + return self + } + /** the closure will be released after consumed. */ @@ -155,6 +163,7 @@ public struct AccumulationSinkIfChanged: Accumulation public consuming func receive(other: consuming AccumulationSinkIfChanged) -> Self { self.previousValue = other.latestValue + self.counter = other.counter return self } @@ -166,7 +175,10 @@ public struct AccumulationSinkIfChanged: Accumulation } if latestValue != previousValue { - handler(latestValue!) + if counter >= countToEmit { + handler(latestValue!) + } + counter += 1 } self.handler = nil diff --git a/Tests/VergeTests/AccumulationTests.swift b/Tests/VergeTests/AccumulationTests.swift index 2315a3203a..33d96784a4 100644 --- a/Tests/VergeTests/AccumulationTests.swift +++ b/Tests/VergeTests/AccumulationTests.swift @@ -64,6 +64,36 @@ final class AccumulationTests: XCTestCase { let _ = sub } + func test_drop() { + + let store = DemoStore() + + let expForCount = expectation(description: "count") + expForCount.expectedFulfillmentCount = 1 + + let sub = store.accumulate(queue: .mainIsolated()) { [weak self] in + + $0.ifChanged(\.count) + .dropFirst(2) + .do { value in + expForCount.fulfill() + } + + } + + store.commit { + $0.count += 1 + } + + store.commit { + $0.count += 1 + } + + wait(for: [expForCount], timeout: 1) + + let _ = sub + } + func test_background() { let store = DemoStore()