DispatchGroup
You can use integrate DispatchGroup on execute method.
ExampleService.swift
import VFNetwork
import Foundation
class HomeService: RequestService<HomeAPI> {
let group = DispatchGroup()
func getJokes(completion: @escaping (Result<HomeModel, Error>, _ group: DispatchGroup) -> Void) {
execute(.home, responseType: HomeModel.self, group: group, completion: completion)
}
func getCategories(completion: @escaping (Result<HomeCategories, Error>, _ group: DispatchGroup) -> Void) {
execute(.categories, responseType: HomeCategories.self, group: group, completion: completion)
}
}
and execute in your viewModel using leave() to terminate group independent execution.
ExampleViewModel.swift
func getJokes(completion: @escaping (Result<HomeModel, Error>) -> Void) {
service.getJokes { result, group in
group.leave()
switch result {
case let .success(joke):
completion(.success(joke))
case let .failure(error):
completion(.failure(error))
}
}
}
func getCategories() {
service.getCategories { result, group in
group.leave()
switch result {
case let .success(categories):
break
case let .failure(error):
print(error)
}
}
}
in your ViewController intercept your group to receive action when your group is finish.
ExampleViewController.swift
func fetch() {
viewModel.getJokes { result in
switch result {
case let .success(jokes):
break
case let .failure(error):
debugPrint(error)
}
}
viewModel.getCategories()
viewModel.service.group.notify(queue: .main) {
print("Services Finished.")
}
}