Skip to content

A collection of useful extensions for Combine and CombineX

License

Notifications You must be signed in to change notification settings

cx-org/CXExtensions

Repository files navigation

CXExtensions

GitHub CI Install Supported Platform Discord

A collection of useful extensions for Combine.

CXExtensions is Combine Compatible Package. You're free to switch underlying Combine implementation between CombineX and Combine.

Installation

Add the following line to the dependencies in your Package.swift file:

.package(url: "https://github.com/cx-org/CXExtensions", .upToNextMinor(from: "0.4.0")),

Requirements

  • Swift 5.0

Operators


IgnoreError

Ignore error from upstream and complete.

// Output: (data: Data, response: URLResponse), Failure: URLError
let upstream = URLSession.shared.cx.dataTaskPublisher(for: url)

// Output: (data: Data, response: URLResponse), Failure: Never
let pub = upstream.ignoreError()

WeakAssign

Like Subscribers.Assign, but capture its target weakly.

pub.assign(to: \.output, weaklyOn: self)

Invoke

Invoke method on an object with each element from a Publisher.

pub.invoke(handleOutput, weaklyOn: self)
//  Substitute for the following common pattern:
//
//      pub.sink { [weak self] output in
//          self?.handleOutput(output)
//      }

Signal

Emits a signal (Void()) whenever upstream publisher produce an element. It's useful when you want Invoke a parameterless handler.

// Transform elements to signal first because `handleSignal` accept no argument.
pub.signal().invoke(handleSignal, weaklyOn: self)

Blocking

Get element from a Publisher synchronously. It's useful for command line tool and unit testing.

let sequence = pub.blocking()
for value in sequence {
    // process value
}

DelayedAutoCancellable

Auto cancel after delay.

let delayedCanceller = upstream
    .sink { o in
        print(o)
    }
    .cancel(after .second(1), scheduler: DispatchQueue.main.cx)