Vasily
Vasily

Reputation: 3790

How to add Combine compatibility to custom classes with older iOS support?

I create a framework and I want to support early adopters of Combine and SwiftUI for some of my providers without dropping prior iOS version support. I like declarative style and I often use observable classes/structures for variable states that could be used by a developer. How to add Combine's support without dropping iOS10+ support and without coding two different classes?

I planned to add #if canImport(Combine) extension to such classes so iOS13 users could use it in a native way without writing custom stores. So they could just call .sink or .assign for example and they will receive updates.

I don't know what protocol to adopt. I thought that store is a Publisher, but Publisher can't use .send method when something changes and I don't know how to notify Subscriber so.

public class SomeDataProvider<T> {
    private var didChangeHandler: ((T?) -> Void)?

    public var value: T? {
        didSet {
            didChangeHandler?(value)
        }
    }
    public func didChange(handler: @escaping ((T?) -> Void)) {
        self.didChangeHandler = handler
    }

    public init() {}
}

The best approach also is to emulate at least .sink (most usable) for prior versions of iOS, so we don't use two separate methods or different iOS versions.

Upvotes: 1

Views: 482

Answers (1)

ytyubox
ytyubox

Reputation: 175

This is something that this repo (OpenCombine) is handling, the idea you have is really great but Combine is too complicated to build. The project is in early development, that's because Combine is new to the world.

Upvotes: 1

Related Questions