another.im-ios/ConversationsClassic/AppCore/Middlewares/ChatsMiddleware.swift

33 lines
1.3 KiB
Swift
Raw Normal View History

2024-06-19 15:15:27 +00:00
import Combine
final class ChatsMiddleware {
static let shared = ChatsMiddleware()
2024-06-20 05:27:13 +00:00
func middleware(state: AppState, action: AppAction) -> AnyPublisher<AppAction, Never> {
2024-06-19 15:15:27 +00:00
switch action {
case .databaseAction(.storedChatsLoaded(let chats)):
return Just(.chatsAction(.chatsListUpdated(chats: chats)))
.eraseToAnyPublisher()
2024-06-20 05:27:13 +00:00
case .chatsAction(.startChat(accountJid: let accountJid, participantJid: let participantJid)):
return Future<AppAction, Never> { promise in
2024-06-20 05:43:49 +00:00
if let exist = state.chatsState.chats.first(where: { $0.account == accountJid && $0.participant == participantJid }) {
// open existing chat
promise(.success(.chatsAction(.chatStarted(chat: exist))))
} else {
// create new chat
promise(.success(.chatsAction(.createNewChat(accountJid: accountJid, participantJid: participantJid))))
2024-06-20 05:27:13 +00:00
}
}
.eraseToAnyPublisher()
2024-06-20 05:43:49 +00:00
case .chatsAction(.chatCreated(let chat)):
return Just(.chatsAction(.chatStarted(chat: chat)))
.eraseToAnyPublisher()
2024-06-19 15:15:27 +00:00
default:
return Empty().eraseToAnyPublisher()
}
}
}