Last active
July 18, 2021 10:16
-
-
Save ykpoh/e80a0ad7a6856ffdfca18ccccdb78dae to your computer and use it in GitHub Desktop.
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
protocol LaunchListViewModelType { | |
var launchViewModels: BehaviorRelay<[LaunchListTableViewCellViewModel]> { get } // 1 | |
var notifyError: BehaviorRelay<Error?> { get } // 2 | |
func fetchLaunchesWithQuery() // 3 | |
} | |
class LaunchListViewModel: LaunchListViewModelType { | |
let apiService: APIServiceProtocol // 4 | |
var launchViewModels = BehaviorRelay<[LaunchListTableViewCellViewModel]>(value: []) | |
var notifyError = BehaviorRelay<Error?>(value: nil) | |
init(apiService: APIServiceProtocol = APIService()) { // 5 | |
self.apiService = apiService | |
fetchLaunchesWithQuery() | |
} | |
func fetchLaunchesWithQuery() { | |
apiService.fetchLaunchesWithQuery { [weak self] (launchResponse, error, _) in | |
guard let strongSelf = self else { return } | |
if let launchResponse = launchResponse { | |
strongSelf.processFetchedLaunches(launchResponse: launchResponse) | |
} else if let error = error { | |
strongSelf.notifyError.accept(error) | |
} | |
} | |
} | |
func processFetchedLaunches(launchResponse: LaunchResponse) { // 6 | |
guard let launches = launchResponse.docs else { return } | |
launchViewModels.accept(convertLaunchesToLaunchListTableViewCellViewModels(launches: launches)) | |
} | |
func convertLaunchesToLaunchListTableViewCellViewModels(launches: [Launch]) -> [LaunchListTableViewCellViewModel] { // 7 | |
var launchListTableViewCellViewModels: [LaunchListTableViewCellViewModel] = [] | |
for launch in launches { | |
launchListTableViewCellViewModels.append(LaunchListTableViewCellViewModel(launch: launch)) | |
} | |
return launchListTableViewCellViewModels | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment