Combine
02 / 02

Combine Fundamentals: Publishers, Subscribers & Operators

Combine: Publishers, Subscribers & Operators

Combine is Apple's native reactive programming framework for processing asynchronous, reactive event streams over time -- network responses, user input, notifications -- using composable, declarative operators.

Publisher, Subscriber, Operator

let cancellable = urlPublisher
  .map { $0.data }
  .decode(type: User.self, decoder: JSONDecoder())
  .receive(on: DispatchQueue.main)
  .sink(
    receiveCompletion: { completion in },
    receiveValue: { user in print(user.name) }
  )

// map/decode are operators transforming the stream;
// sink is the subscriber receiving final values

@Published & ObservableObject

class ProfileModel: ObservableObject {
  @Published var name: String = ""
}

// SwiftUI observes the synthesized objectWillChange publisher,
// automatically triggered whenever a @Published property changes,
// and re-renders views observing this object

Managing Subscription Lifetime

class ViewModel {
  var cancellables = Set<AnyCancellable>()

  func subscribe() {
    publisher.sink { value in }.store(in: &cancellables)
  }
}

// If the AnyCancellable isn't retained, the subscription is
// torn down almost immediately -- always store it somewhere

Debouncing Rapid Input

$searchText
  .debounce(for: .milliseconds(300), scheduler: RunLoop.main)
  .sink { query in performSearch(query) }
  .store(in: &cancellables)

// Waits for a pause in typing before firing a network
// request -- avoids one request per keystroke

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free