Swiftpack.co - manmal/CombineLifetime as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by manmal.
manmal/CombineLifetime 1.0.0
For when Set<AnyCancellable> is too limiting
⭐️ 0
🕓 2 years ago
iOS macOS watchOS tvOS
.package(url: "https://github.com/manmal/CombineLifetime.git", from: "1.0.0")

CombineLifetime

When subscribing to a Swift Combine Publisher, we use a Set<AnyCancellable> most of the time, like this:

publisher
  .sink { value in
    // Do something with value
  }
  .store(in: &cancellables)

The problem with this is that Set is a value type, so it cannot be mutated if the owner is immutable. It is painful to use when the Set<AnyCancellable> needs to be stored in a struct or enum.

The solution for this is Lifetime, heavily inspired by ReactiveSwift's implementation. It's a final class, wraps a Set<AnyCancellable>, conforms to Cancellable and Hashable, and offers a convenient += operator:

lifetime += publisher
  .sink { value in
    // Do something with value
  }

Like any other Cancellable, it cancels the work automatically when it is deallocated, so make sure to keep its instance around.

Contact

🐦 Contact me via Twitter @manuelmaly

1.0.0

  • Added initial implementation and tests

GitHub

link
Stars: 0
Last commit: 2 years ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics