Skip to content

Instantly share code, notes, and snippets.

@eliakorkmaz
Created February 20, 2023 22:48
Show Gist options
  • Save eliakorkmaz/4f53f6bbbfcb9e2c55f0b3cb07f27850 to your computer and use it in GitHub Desktop.
Save eliakorkmaz/4f53f6bbbfcb9e2c55f0b3cb07f27850 to your computer and use it in GitHub Desktop.
import Foundation
protocol ProfileViewModelWorkable {
func fetchProfileAndTagIt(completion: @escaping (Bool) -> Void)
}
class ProfileViewModelWorker: ProfileViewModelWorkable {
func fetchProfileAndTagIt(completion: @escaping (Bool) -> Void) {
fetchProfile { [weak self] result in
guard let self = self else {return}
self.tagAnalytics(result: result, completion: completion)
}
}
}
private protocol ProfileNetworkFetchable {
func fetchProfile(completion: @escaping (Result<Profile,NSError>) -> Void)
}
private protocol ProfileAnalyticTaggable {
func tagAnalytics(result: Result<Profile,NSError>, completion: @escaping (Bool) -> Void)
}
extension ProfileViewModelWorker: ProfileNetworkFetchable, ProfileAnalyticTaggable {
func tagAnalytics(result: Result<Profile, NSError>, completion: @escaping (Bool) -> Void) {
switch result {
case .success(_):
print("trigger analytics with success.......")
completion(true)
case .failure(_):
print("trigger analytics with error.........")
completion(true)
}
}
func fetchProfile(completion: @escaping (Result<Profile,NSError>) -> Void) {
let url = URL.init(string: "https://www.awesomewebservice.com/profile")!
let urlRequest = URLRequest(url: url)
let dataTask = URLSession.shared.dataTask(with: urlRequest) { data, _, _ in
guard let data = data else {
completion(.failure(NSError()))
return
}
guard let profileDecoded = try? JSONDecoder().decode(Profile.self, from: data) else {
completion(.failure(NSError()))
return
}
completion(.success(profileDecoded))
}
dataTask.resume()
}
}
class ProfileViewModel {
var viewModelWorkable: ProfileViewModelWorkable
init(viewModelWorkable: ProfileViewModelWorkable) {
self.viewModelWorkable = viewModelWorkable
}
}
extension ProfileViewModel {
func fetchAndTag() {
viewModelWorkable.fetchProfileAndTagIt { success in
if success {
print("profile is fetched and tagged")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment