Last active
May 10, 2024 10:56
-
-
Save saoudrizwan/dd25978e82eba27138361c5a2b5c4457 to your computer and use it in GitHub Desktop.
Handle multiple network requests with the same URL efficiently with a shared task manager
This file contains 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 | |
class TaskManager { | |
static let shared = TaskManager() | |
let session = URLSession(configuration: .default) | |
typealias completionHandler = (Data?, URLResponse?, Error?) -> Void | |
var tasks = [URL: [completionHandler]]() | |
func dataTask(with url: URL, completion: @escaping completionHandler) { | |
if tasks.keys.contains(url) { | |
tasks[url]?.append(completion) | |
} else { | |
tasks[url] = [completion] | |
let _ = session.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in | |
DispatchQueue.main.async { | |
print("Finished network task") | |
guard let completionHandlers = self?.tasks[url] else { return } | |
for handler in completionHandlers { | |
print("Executing completion block") | |
handler(data, response, error) | |
} | |
} | |
}).resume() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment