Created
September 5, 2021 04:28
-
-
Save ytyubox/de5b27ec827c66195c4c3cde05f71760 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
/* | |
* Created by 游宗諭 in 2021/9/2 | |
* | |
* Using Swift 5.0 | |
* | |
* Running on macOS 12.0 | |
*/ | |
import Foundation | |
// MARK: - Interface Define | |
protocol MySubscription { | |
func askValue() | |
} | |
protocol MyPublisher { | |
func register(to subscriber: MySubscriber) | |
} | |
enum AskAgain { | |
case yes, no | |
} | |
protocol MySubscriber { | |
func takeAction(for value: Int) -> AskAgain | |
func register(to subscription: MySubscription) | |
} | |
// MARK: - Test Helper | |
class PlainPublisher: MyPublisher { | |
func register(to subscriber: MySubscriber) { | |
let mySubscription = StubSubscription(mySubscriber: subscriber) | |
subscriber.register(to: mySubscription) | |
} | |
} | |
class StubSubscription: MySubscription { | |
let mySubscriber: MySubscriber | |
var value = 0 | |
init(mySubscriber: MySubscriber) { | |
self.mySubscriber = mySubscriber | |
} | |
func askValue() { | |
while true { | |
value += 1 | |
let askAgain = mySubscriber.takeAction(for: value) | |
if askAgain == .no {break} | |
} | |
} | |
} | |
class StubSubscriber: MySubscriber { | |
var _takeAction: (Int) -> Void | |
var askAgain:() -> AskAgain | |
internal init(_takeAction: @escaping (Int) -> Void, askAgain: @escaping () -> AskAgain) { | |
self._takeAction = _takeAction | |
self.askAgain = askAgain | |
} | |
func takeAction(for value: Int) -> AskAgain { | |
_takeAction(value) | |
return askAgain() | |
} | |
func register(to subscription: MySubscription) { | |
subscription.askValue() | |
} | |
} | |
// MARK: - TestCase | |
import XCTest | |
final class CombineProtocolsTests: XCTestCase { | |
func testShowHowTheCombineProtocolsInteract() throws { | |
var history:[Int] = [] | |
let publisher = PlainPublisher() | |
var count = 0 | |
let scriber = StubSubscriber { | |
history.append($0) | |
} askAgain: { | |
count += 1 | |
return count < 3 ? .yes : .no | |
} | |
publisher.register(to: scriber) | |
XCTAssertEqual(history, [1, 2, 3]) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Idea from Open Combine Just
https://github.com/OpenCombine/OpenCombine/blob/master/Sources/OpenCombine/Publishers/Just.swift