Skip to content

Instantly share code, notes, and snippets.

@filimo
Last active August 4, 2021 09:29
Show Gist options
  • Save filimo/6f826b352f75cd1640e4e705340c0301 to your computer and use it in GitHub Desktop.
Save filimo/6f826b352f75cd1640e4e705340c0301 to your computer and use it in GitHub Desktop.
//
// CancelBag.swift
// CountriesSwiftUI
//
// Created by Alexey Naumov on 04.04.2020.
// Copyright © 2020 Alexey Naumov. All rights reserved.
//
import Combine
import SwiftUI
final class CancelBag {
var subscriptions = Set<AnyCancellable>()
func cancel() {
subscriptions.forEach { $0.cancel() }
subscriptions.removeAll()
}
func collect(@Builder _ cancellables: () -> [AnyCancellable]) {
subscriptions.formUnion(cancellables())
}
@_functionBuilder
struct Builder {
static func buildBlock(_ cancellables: AnyCancellable...) -> [AnyCancellable] {
return cancellables
}
}
}
extension AnyCancellable {
func store(in cancelBag: CancelBag) {
cancelBag.subscriptions.insert(self)
}
}
class ViewModel: ObservableObject {
private var cancelBag = CancelBag()
@Published var publisher1: Int = 0
@Published var publisher2: String = "s0"
init() {
cancelBag.collect {
$publisher1.sink { print($0) }
$publisher2
.removeDuplicates()
.sink { print($0) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment