中文)
CXCompatible(CXCompatible provides compatibility shims for CombineX. Using it, you can write code that is compatible with both Combine and CombineX. In other words, you can freely switch dependencies between Combine and CombineX without modifying the code base.
#if USE_COMBINE
import CXFoundation
#else
import CXCompatible
#endif
let task = Timer.cx.publish(every: 1, on: RunLoop.main, in: .default)
.sink { date in
// task
}
Combine
enables many system types to support Publisher
, for example:
let nums = [0, 1, 2].publisher
let task = URLSession.share.dataTaskPublisher(for: endpoint)
Why do I need CXCompatible
You should already know CombineX
, which is an open source implementation of Combine. Its purpose is to provide a completely consistent API with Combine, freeing you from the limitations of the version and platform. This sounds great, isn't it? But the implementation has encountered some trouble.
Combine directly extends some system types and provides them with a pub-sub interface, such as:
let nums = [0, 1, 2].publisher
let task = URLSession.share.dataTaskPublisher(for: endpoint)
CombineX tries to provide the same functionality, but unfortunately it can't use the same API, such as:
extension Sequence {
// Error: ambiguous use of ...
public var publisher: Publishers.Sequence {
// ...
}
}
extension URLSession {
// Swift doesn't allow you to define the same name again, even in a different framework.
public struct DataTaskPublisher: Publisher {
// ...
}
}
CombineX's solution is cx
:
let nums = [1, 2, 3].cx.publisher
let task = URLSession.share.cx.dataTaskPublisher(for: endpoint)
Yes, this breaks the consistency of CombineX and Combine. To make this code compatible with Combine, CXCompatible implements an alternative implementation of all cx
interfaces, but based on Combine.
Install
Swift Package Manager
dependencies.append(
.package(url: "https://github.com/cx-org/CXCompatible", .branch("master"))
)
CocoaPods
pod 'CXCompatible', :git => 'https://github.com/cx-org/CXCompatible.git', :branch => 'master'
Carthage
github "cx-org/CXCompatible" "master"