Visual_Novel_iOS/crush/Crush/Src/Utils/Extensions/CombineExt.swift

59 lines
1.8 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// CombineExt.swift
// Crush
//
// Created by Leon on 2025/8/7.
//
import Combine
import UIKit
extension UITextField {
var textPublisher: AnyPublisher<String?, Never> {
NotificationCenter.default.publisher(for: UITextField.textDidChangeNotification, object: self)
.map { ($0.object as? UITextField)?.text }
.eraseToAnyPublisher()
}
}
extension UITextView {
var textPublisher: AnyPublisher<String?, Never> {
NotificationCenter.default
.publisher(for: UITextView.textDidChangeNotification, object: self)
.map { ($0.object as? UITextView)?.text }
.eraseToAnyPublisher()
}
}
extension Publishers {
/*
使
Publishers.eitherLatest(container.$whoIm, container.$birthdayDate)
.sink { whoIm, birthday in
// whoIm: String?
// birthday: Date?
print(" -> whoIm=\(whoIm ?? "nil"), birthday=\(birthday?.description ?? "nil")")
}
.store(in: &cancellables)
*/
/// Optional
static func eitherLatest<A, B, P1: Publisher, P2: Publisher>(
_ p1: P1,
_ p2: P2
) -> AnyPublisher<(A?, B?), Never>
where P1.Output == A?, P2.Output == B?, P1.Failure == Never, P2.Failure == Never {
let left = p1.map { value -> (A?, B?) in (value, nil as B?) }
let right = p2.map { value -> (A?, B?) in (nil as A?, value) }
return Publishers.Merge(left, right)
// nil nil 沿
.scan((nil as A?, nil as B?)) { last, new in
(new.0 ?? last.0, new.1 ?? last.1)
}
.eraseToAnyPublisher()
}
}