refactor: Fix DataTask cancel() method design issue #42
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
The original code had a design issue where
urlSessionwas created inside theevents()function, but thecancel()method required it as a parameter. This caused the following problems:urlSessiononly existed within the function scope, making it impossible to access the correct session when callingcancel()from outsidecancel()method was public but couldn't receive the correctURLSessioninstance from external callsSolution
_urlSessionMutex variable to theDataTaskclass to manage the session object at the instance levelurlSessionparameters fromhandleSessionError,handleSessionResponse,parseMessages, andclosemethodsnilafter cancellation to prevent memory leaksKey Changes
_urlSession: Mutex<URLSession?>instance variable toDataTaskclasscancel()method signature fromcancel(urlSession: URLSession)tocancel()urlSessionparameter from all related methodsurlSession = nilincancel()method for better memory managementBenefits
cancel()method can now accurately cancel the session that's actually in usecancel()method is more intuitive to call without parametersTesting
Breaking Changes
This change modifies the public API of the
cancel()method. Previously it required aURLSessionparameter, now it doesn't require any parameters. This is a breaking change but improves the API design significantly.Related Issues
Fixes the design issue where external calls to
cancel()couldn't properly cancel the URLSession due to scope limitations.