SwiftUI Imtiaz Ahmad (iTechnology) - Imtiaz211/interviews GitHub Wiki

How can you use the reduce operator in Combine

  • The reduce operator allows you to accumulate the values emitted by a publisher and return the final result.
let numbers = [1, 2, 3, 4, 5]
@State private var cancellable = Set<AnyCancellable>()
let publisher = numbers.publisher

publisher
    .reduce(0, +)
    .sink(receiveValue: { sum in
        print("The sum is: \(sum)")
    })
    .store(in: &cancellables)

How can you use the scan operator in Combine?

  • The scan operator is similar to reduce, but it emits the intermediate results as well as the final result.
let numbers = [1, 2, 3, 4, 5]
@State private var cancellable = Set<AnyCancellable>()
let publisher = numbers.publisher

publisher
    .scan(0, +)
    .sink(receiveValue: { total in
        print("The running total is: \(total)")
    })
    .store(in: &cancellables)

How can you use the debounce operator in Combine?

  • The debounce operator allows you to delay the emission of values by a certain amount of time.
private var bag = Set<AnyCancellable>()

let future = Future<Int, Never> { promise in
    promise(.success(1))
}

future
.debounce(for: .seconds(0.5), scheduler: DispatchQueue.main)
.sink(
    receiveCompletion: { 
         print($0) // Called
    },
    receiveValue: { 
        print($0)  // Not called
    }
)
.store(in: &bag)

How can you use the map operator in Combine?

  • The map operator allows you to transform the values emitted by a publisher.
let numbers = [1, 2, 3, 4, 5]
@State private var cancellable = Set<AnyCancellable>()
let publisher = numbers.publisher

publisher
    .map { $0 * $0 }
    .sink(receiveValue: { value in
        print("The squared value is: \(value)")
    })
    .store(in: &cancellables)

How can you use the zip operator in Combine?

  • The zip operator allows you to combine the values emitted by two or more publishers.
let namePublisher = user.namePublisher
let agePublisher = user.agePublisher
@State private var cancellable = Set<AnyCancellable>()
Publishers.Zip(namePublisher, agePublisher)
    .sink(receiveValue: { name, age in
        print("Name: \(name), Age: \(age)")
    })
    .store(in: &cancellables)

How can you use the flatMap operator in Combine?

  • The flatMap operator allows you to transform the values emitted by a publisher and then flatten the resulting publishers into a single publisher.
let publisher = URLSession.shared.dataTaskPublisher(for: url)
    .map { $0.data }
    .decode(type: User.self, decoder: JSONDecoder())
    .flatMap { user in
        user.fetchAvatar()
    }
    .sink(receiveCompletion: { completion in
        switch completion {
        case .failure(let error):
            print(error)
        case .finished:
            break
        }
    }, receiveValue: { avatar in
        // update UI with avatar
    })

How can you use the compactMap operator in Combine?

  • The compactMap operator allows you to transform the values emitted by a publisher and filter out nil values.
@State private var cancellable = Set<AnyCancellable>()
let publisher = emailTextField.publisher(for: .editingChanged)
    .map { $0.text }
    .compactMap { email in
        guard email.isValidEmail() else { return nil }
        return email
    }
    .sink(receiveValue: { email in
        print("Valid email: \(email)")
    })
    .store(in: &cancellables)

How can you use the throttle operator in Combine?

  • The throttle operator allows you to limit the frequency of the values emitted by a publisher.
let publisher = searchTextField.publisher(for: .editingChanged)
    .map { $0.text }
    .throttle(for: .seconds(1), scheduler: DispatchQueue.main, latest: true)

How can you use the filter operator in Combine?

  • The filter operator allows you to filter out values emitted by a publisher based on a certain condition.
let numbers = [1, 2, 3, 4, 5]
@State private var cancellable = Set<AnyCancellable>()
let publisher = numbers.publisher

publisher
    .filter { $0 % 2 == 0 }
    .sink(receiveValue: { value in
        print("Even number: \(value)")
    })
    .store(in: &cancellables)

How can you use the merge operator in Combine?

  • The merge operator allows you to merge multiple publishers into a single publisher.
@State private var cancellable = Set<AnyCancellable>()
let publisher1 = NotificationCenter.default.publisher(for: .event1)
let publisher2 = NotificationCenter.default.publisher(for: .event2)

Publishers.Merge(publisher1, publisher2)
    .sink(receiveValue: { event in
        switch event {
        case .event1(let value):
            print("Event 1: \(value)")
        case .event2(let value):
            print("Event 2: \(value)")
        }
    })
    .store(in: &cancellables)

How can you use the combineLatest operator in Combine?

  • The combineLatest operator allows you to combine the latest values emitted by multiple publishers.
let namePublisher = user.namePublisher
let agePublisher = user.agePublisher
@State private var cancellable = Set<AnyCancellable>()
Publishers.CombineLatest(namePublisher, agePublisher)
    .sink(receiveValue: { name, age in
        print("Name: \(name), Age: \(age)")
    })
    .store(in: &cancellables)

How can you use the buffer operator in Combine?

  • The buffer operator allows you to buffer the values emitted by a publisher and emit them as an array.
let publisher = somePublisher
@State private var cancellable = Set<AnyCancellable>()
publisher
    .buffer(timeSpan: 3, scheduler: DispatchQueue.main)
    .sink(receiveValue: { values in
        print("Buffered values: \(values)")
    })
    .store(in: &cancellables)

How can you use the distinctUntilChanged operator in Combine?

  • The distinctUntilChanged operator allows you to only receive unique values emitted by a publisher.
let publisher = somePublisher
@State private var cancellable = Set<AnyCancellable>()
publisher
    .distinctUntilChanged()
    .sink(receiveValue: { value in
        print("Unique value: \(value)")
    })
    .store(in: &cancellables)
⚠️ **GitHub.com Fallback** ⚠️