@@ -6,6 +6,8 @@ import com.apollographql.apollo.api.http.HttpRequest
6
6
import com.apollographql.apollo.api.http.HttpResponse
7
7
import com.apollographql.apollo.exception.ApolloNetworkException
8
8
import com.apollographql.apollo.network.toNSData
9
+ import kotlinx.atomicfu.locks.reentrantLock
10
+ import kotlinx.atomicfu.locks.withLock
9
11
import kotlinx.cinterop.alloc
10
12
import kotlinx.cinterop.nativeHeap
11
13
import kotlinx.cinterop.ptr
@@ -207,6 +209,8 @@ private class StreamingDataDelegate : NSObject(), NSURLSessionDataDelegateProtoc
207
209
fun onComplete (error : NSError ? )
208
210
}
209
211
212
+ private val lock = reentrantLock()
213
+
210
214
private val handlers = mutableMapOf<NSURLSessionTask , Handler >()
211
215
212
216
override fun URLSession (
@@ -215,7 +219,9 @@ private class StreamingDataDelegate : NSObject(), NSURLSessionDataDelegateProtoc
215
219
didReceiveResponse : NSURLResponse ,
216
220
completionHandler : (NSURLSessionResponseDisposition ) -> Unit ,
217
221
) {
218
- handlers[dataTask]?.onResponse(didReceiveResponse as NSHTTPURLResponse )
222
+ lock.withLock {
223
+ handlers[dataTask]
224
+ }?.onResponse(didReceiveResponse as NSHTTPURLResponse )
219
225
completionHandler(NSURLSessionResponseAllow )
220
226
}
221
227
@@ -224,18 +230,22 @@ private class StreamingDataDelegate : NSObject(), NSURLSessionDataDelegateProtoc
224
230
dataTask : NSURLSessionDataTask ,
225
231
didReceiveData : NSData ,
226
232
) {
227
- handlers[dataTask]?.onData(didReceiveData)
233
+ lock.withLock {
234
+ handlers[dataTask]
235
+ }?.onData(didReceiveData)
228
236
}
229
237
230
238
override fun URLSession (
231
239
session : NSURLSession ,
232
240
task : NSURLSessionTask ,
233
241
didCompleteWithError : NSError ? ,
234
242
) {
235
- handlers[task]?.onComplete(didCompleteWithError)
236
-
237
- // Cleanup
238
- handlers.remove(task)
243
+ lock.withLock {
244
+ handlers[task].also {
245
+ // Cleanup
246
+ handlers.remove(task)
247
+ }
248
+ }?.onComplete(didCompleteWithError)
239
249
}
240
250
241
251
override fun URLSession (
@@ -244,16 +254,20 @@ private class StreamingDataDelegate : NSObject(), NSURLSessionDataDelegateProtoc
244
254
willCacheResponse : NSCachedURLResponse ,
245
255
completionHandler : (NSCachedURLResponse ? ) -> Unit ,
246
256
) {
247
- handlers[dataTask]?.onComplete(null )
248
-
249
- // Cleanup
250
- handlers.remove(dataTask)
257
+ lock.withLock {
258
+ handlers[dataTask].also {
259
+ // Cleanup
260
+ handlers.remove(dataTask)
261
+ }
262
+ }?.onComplete(null )
251
263
252
264
completionHandler(willCacheResponse)
253
265
}
254
266
255
267
fun registerHandlerForTask (task : NSURLSessionTask , handler : Handler ) {
256
- handlers[task] = handler
268
+ lock.withLock {
269
+ handlers[task] = handler
270
+ }
257
271
}
258
272
}
259
273
0 commit comments