Skip to content

Commit

Permalink
Add dropFirst in Accumulation (#486)
Browse files Browse the repository at this point in the history
  • Loading branch information
muukii authored Jun 27, 2024
1 parent 763855f commit da0f2b6
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
14 changes: 13 additions & 1 deletion Sources/Verge/Store/StoreDriverType+Accumulator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ public struct AccumulationSinkIfChanged<Source, Target: Equatable>: 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(
Expand All @@ -137,6 +140,11 @@ public struct AccumulationSinkIfChanged<Source, Target: Equatable>: Accumulation
self.selector = selector
}

public consuming func dropFirst(_ k: Int = 1) -> Self {
countToEmit = k
return self
}

/**
the closure will be released after consumed.
*/
Expand All @@ -155,6 +163,7 @@ public struct AccumulationSinkIfChanged<Source, Target: Equatable>: Accumulation
public consuming func receive(other: consuming AccumulationSinkIfChanged<Source, Target>) -> Self {

self.previousValue = other.latestValue
self.counter = other.counter

return self
}
Expand All @@ -166,7 +175,10 @@ public struct AccumulationSinkIfChanged<Source, Target: Equatable>: Accumulation
}

if latestValue != previousValue {
handler(latestValue!)
if counter >= countToEmit {
handler(latestValue!)
}
counter += 1
}

self.handler = nil
Expand Down
30 changes: 30 additions & 0 deletions Tests/VergeTests/AccumulationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit da0f2b6

Please sign in to comment.