Last active
March 23, 2021 23:16
-
-
Save karenxpn/325adf3d15a5396a977c73a92b5b41c0 to your computer and use it in GitHub Desktop.
Chat ViewModel that will give us the list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Combine | |
class ViewModel: ObservableObject { | |
@Published var chats = [ChatModel]() | |
@Published var chatListLoadingError: String = "" | |
@Published var showAlert: Bool = false | |
private var cancellableSet: Set<AnyCancellable> = [] | |
var dataManager: ServiceProtocol | |
init( dataManager: ServiceProtocol = Service.shared) { | |
self.dataManager = dataManager | |
getChatList() | |
} | |
func getChatList() { | |
dataManager.fetchChats() | |
.sink { (dataResponse) in | |
if dataResponse.error != nil { | |
self.createAlert(with: dataResponse.error!) | |
} else { | |
self.chats = dataResponse.value!.chats | |
} | |
}.store(in: &cancellableSet) | |
} | |
func createAlert( with error: NetworkError ) { | |
chatListLoadingError = error.backendError == nil ? error.initialError.localizedDescription : error.backendError!.message | |
self.showAlert = true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment