4

Extension for a Combine-Publisher that returns the current and previous value.

 2 years ago
source link: https://gist.github.com/fxm90/be62335d987016c84d2f8b3731197c98
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Author

fxm90 commented on May 17, 2021

Related test case:

class PairwiseTestCase: XCTestCase {

    func testPairwise() {
        // Given
        // We can't conform a tuple to `Equatable`, therefore we map the tuples to a struct.
        // We also can't define a struct in a protocol extension, therefore we used a `typealias` in the implementation.
        struct Pairwise<T: Equatable>: Equatable {
            let previous: T?
            let current: T
        }

        var receivedPairs = [Pairwise<Int>]()

        let range = 1 ... 5
        var subscriptions = Set<AnyCancellable>()

        // When
        range.publisher
            .pairwise()
            .sink {
                receivedPairs.append(Pairwise(previous: $0.previous, current: $0.current))
            }
            .store(in: &subscriptions)

        // Then
        XCTAssertEqual(receivedPairs, [
            Pairwise(previous: nil, current: 1),
            Pairwise(previous: 1, current: 2),
            Pairwise(previous: 2, current: 3),
            Pairwise(previous: 3, current: 4),
            Pairwise(previous: 4, current: 5),
        ])
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK