Skip to content

Instantly share code, notes, and snippets.

@bok-
Created August 8, 2019 07:36
Show Gist options
  • Save bok-/ddebda3e4290164d6589ed26f602fe06 to your computer and use it in GitHub Desktop.
Save bok-/ddebda3e4290164d6589ed26f602fe06 to your computer and use it in GitHub Desktop.
import Foundation
import Combine
@_functionBuilder
public struct AnyCancellableBuilder {
public static func buildBlock () -> [AnyCancellable] {
return []
}
public static func buildBlock (_ child: AnyCancellable) -> [AnyCancellable] {
return [child]
}
public static func buildBlock (_ children: AnyCancellable...) -> [AnyCancellable] {
return children
}
public static func buildIf (_ children: AnyCancellable?) -> [AnyCancellable] {
guard let children = children else { return [] }
return [children]
}
public static func buildEither (first: AnyCancellable) -> [AnyCancellable] {
return [first]
}
public static func buildEither (second: AnyCancellable) -> [AnyCancellable] {
return [second]
}
}
extension Set where Element == AnyCancellable {
public mutating func collect (@AnyCancellableBuilder _ make: () -> AnyCancellable) {
insert(make())
}
public mutating func collect (@AnyCancellableBuilder _ make: () -> [AnyCancellable]) {
make()
.forEach { self.insert($0) }
}
}
func test () {
var bag = Set<AnyCancellable>()
bag.collect {
Just(1234)
.sink { print($0) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment