Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Last active November 13, 2020 20:48
Show Gist options
  • Save mbrandonw/cb4848c9896680af6d250d9ae5f15cdd to your computer and use it in GitHub Desktop.
Save mbrandonw/cb4848c9896680af6d250d9ae5f15cdd to your computer and use it in GitHub Desktop.
extension Effect {
func cancellable<Id: Hashable>(id: Id) -> Effect<Output> {
return Deferred { () -> PassthroughSubject<Output, Failure> in
cancellables[id]?.cancel()
let subject = PassthroughSubject<Output, Failure>()
cancellables[id] = self.subscribe(subject)
return subject
}
.eraseToEffect()
}
}
extension Effect where Output == Never {
static func cancel<Id: Hashable>(id: Id) -> Effect {
.fireAndForget {
cancellables[id]?.cancel()
cancellables[id] = nil
}
}
}
private var cancellables: [AnyHashable: AnyCancellable] = [:]
@damirstuhec
Copy link

👍

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