Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Created September 5, 2021 04:28
Show Gist options
  • Save ytyubox/de5b27ec827c66195c4c3cde05f71760 to your computer and use it in GitHub Desktop.
Save ytyubox/de5b27ec827c66195c4c3cde05f71760 to your computer and use it in GitHub Desktop.
//
/*
* 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])
}
}
@ytyubox
Copy link
Author

ytyubox commented Sep 5, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment