import Combine final class ConversationMiddleware { static let shared = ConversationMiddleware() func middleware(state: AppState, action: AppAction) -> AnyPublisher { switch action { case .chatsAction(.chatStarted(let chat)): return Just(AppAction.conversationAction(.makeConversationActive(chat: chat))).eraseToAnyPublisher() case .conversationAction(.makeConversationActive): return Just(AppAction.changeFlow(.conversation)).eraseToAnyPublisher() case .xmppAction(.xmppMessageReceived(let message)): return Future { promise in let currentChat = state.conversationsState.currentChat if message.from == currentChat?.participant, message.to == currentChat?.account { promise(.success(.conversationAction(.messageForCurrentConversationReceived(message)))) } else { promise(.success(.empty)) } } .eraseToAnyPublisher() default: return Empty().eraseToAnyPublisher() } } }