Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Created August 27, 2022 18:58
Show Gist options
  • Save hmlongco/76113270eb9f59bbb5438c63221f2378 to your computer and use it in GitHub Desktop.
Save hmlongco/76113270eb9f59bbb5438c63221f2378 to your computer and use it in GitHub Desktop.
Subscriptions addition to Combine
//
// Combine+Extensions.swift
// Common
//
// Created by Michael Long on 8/27/22.
//
import Foundation
import Combine
typealias Subscriptions = Set<AnyCancellable>
extension Subscriptions {
public mutating func add(_ subscriptions: AnyCancellable...) {
subscriptions.forEach { self.insert($0) }
}
public mutating func add(@SubscriptionBuilder builder: () -> [AnyCancellable]) {
builder().forEach { self.insert($0) }
}
public mutating func add<SuccessType: Sendable, FailureType: Error>(_ task: Task<SuccessType, FailureType>) {
add(AnyCancellable(task.cancel))
}
public mutating func cancel() {
self = []
}
#if swift(>=5.4)
@resultBuilder
public struct SubscriptionBuilder {
public static func buildBlock(_ subscriptions: AnyCancellable...) -> [AnyCancellable] {
return subscriptions
}
}
#else
@_functionBuilder
public struct SubscriptionBuilder {
public static func buildBlock(_ subscriptions: AnyCancellable...) -> [AnyCancellable] {
return subscriptions
}
}
#endif
}
extension Task where Success == Sendable, Failure == Error {
func store(in container: inout Subscriptions) {
container.add(self)
}
}
func test() {
let publisher1 = CurrentValueSubject<String, Never>("Hello")
let publisher2 = CurrentValueSubject<String, Never>("World")
var subscriptions = Subscriptions()
// variadic
subscriptions.add(
publisher1.sink { string in
print(string)
},
publisher2.sink { string in
print(string)
}
)
// result builder
subscriptions.add {
publisher1.sink { string in
print(string)
}
publisher2.sink { string in
print(string)
}
}
subscriptions.cancel()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment