Last active
August 4, 2021 09:29
-
-
Save filimo/6f826b352f75cd1640e4e705340c0301 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
// | |
// 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) | |
} | |
} |
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
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
Read more
https://gist.github.com/nalexn/33f14af1d163ea476ee499c0459824b2
https://nalexn.github.io/cancelbag-for-combine/