合并iOS自定义主题不发送值

hvvq6cgz  于 2023-10-21  发布在  iOS
关注(0)|答案(1)|浏览(82)

在下面的代码中,我试图创建一个只能发出偶数的自定义主题。由于某种原因,它没有发出任何值。我之前使用了CurrentValueSubject,但那是选择最后一个值。我想发出任何值,只要它是偶数。

class EvenSubject<Failure: Error>: Subject {
    
    typealias Output = Int
    
    private let wrapped: PassthroughSubject<Int, Failure>
    
    init(initialValue: Int) {
        self.wrapped = PassthroughSubject()
        let evenInitialValue = EvenSubject.isEven(value: initialValue) ? initialValue: 0
        send(evenInitialValue)
    }
    
    private static func isEven(value: Int) -> Bool {
        value % 2 == 0
    }
    
    func send(_ value: Output) {
        print("send")
        
        if value % 2 == 0 {
            wrapped.send(value)
        }
        
    }
    
    func send(completion: Subscribers.Completion<Failure>) {
        print("send completion")
        wrapped.send(completion: completion)
    }
    
    func send(subscription: Subscription) {
        print("send subscription")
        wrapped.send(subscription: subscription)
    }
    
    func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input {
        wrapped.receive(subscriber: subscriber)
    }
    
}

let subject = EvenSubject<Never>(initialValue: 4)

subject.send(10)
subject.send(7)
subject.send(14)

let cancellable = subject.sink { _ in
    
} receiveValue: { value in
    print(value)
}
bogh5gae

bogh5gae1#

在这里,你发送值,然后订阅它。

let subject = EvenSubject<Never>(initialValue: 4)

subject.send(10)
subject.send(7)
subject.send(14)

let cancellable = subject.sink { _ in
    
} receiveValue: { value in
    print(value)
}

如果你改变了顺序:

let subject = EvenSubject<Never>(initialValue: 4)

let cancellable = subject.sink { _ in
    
} receiveValue: { value in
    print(value)
}

subject.send(10)
subject.send(7)
subject.send(14)

您将看到输出:10 14

相关问题