I have an event bus that publishes events happening over a custom text field(a chat message input box), like attachMediaEvent, sendMessageEvent, selectTextEvent. I want to provide provide default actions for the events, but only in case downstream doesn't handle it(kind of like how one can provide protocol default implementation). Is there a way to check if the downstream handles the event and handle it if doesn't?
I know that I'm being loose with the phrase handling the event
but it was intentional and I would like any sort of solution for it. And I'm not adding any code, but I can do so, if needed. It is a really simple publisher that pushes events, anyhow.
EDIT:
Ok, I dug deeper in SO and I started to get the idea that I had to implement custom operator. But I have hit the exact same roadblock. I have no idea how a downstream can speak to the upstream about how it has handled its values. Although I tried to create a protocol(EventConsumer
) that one could check if implemented by a object that is passed to the subscriber, but which felt very wrong. Any help would be a godsend.
Here's the code I tried in playground.
@objc protocol EventConsumer {
@objc optional func sendEventAction()
@objc optional func attachEventAction()
}
class DefaultEventConsumer: EventConsumer {
}
struct CustomPublisher<Upstream: Publisher>: Publisher where Upstream.Output == String, Upstream.Failure == Never {
typealias Output = String
typealias Failure = Never
var upstreamEventPublisher: Upstream
// var eventConsumer: EventConsumer
func receive<S>(subscriber: S) where S : Subscriber, Never == S.Failure, String == S.Input {
let subscription = CustomSubscription<S>(/*eventHandler: eventConsumer*/)
subscription.downstream = subscriber
subscriber.receive(subscription: subscription)
upstreamEventPublisher.sink { eventString in
subscription.sendEvent(event: eventString)
}
}
}
class CustomSubscription<Downstream: Subscriber>: Subscription where Downstream.Input == String {
var downstream: Downstream?
// var eventHandler: EventConsumer
// init(eventHandler: EventConsumer) {
// self.eventHandler = eventHandler
// }
func request(_ demand: Subscribers.Demand) {
}
func cancel() {
downstream = nil
}
func sendEvent(event: String) {
//How do I check if downstream processes the event somehow and send event if it doesnt
downstream?.receive(event)
}
}
//
//
//extension AnyPublisher where Output == String, Failure == Never {
//
// func checkAndPublishEvents(_ eventConsumer: EventConsumer) -> Self {
//
// CustomPublisher(upstreamEventPublisher: self/*, eventConsumer: eventConsumer*/)
// .eraseToAnyPublisher()
// }
//}