itnoles
07/17/2021, 2:45 PMsuspend fun fetch() : HttpResponse = suspendCoroutine {
val semaphore = dispatch_semaphore_create(0)
val nativeRequest = NSMutableURLRequest(uRL = NSURL.URLWithString("<https://api.spacexdata.com/v4/launches>")!!)
nativeRequest.setHTTPMethod("GET")
val result = AtomicReference(HttpResponse().freeze())
val completionHandler = { nsData: NSData?, nsURLResponse: NSURLResponse?, nsError: NSError? ->
if (nsError != null) {
val message =
"The response is: " + nsURLResponse?.description() + ", error is: " + nsError.description()
println(message)
}
val response = nsURLResponse as NSHTTPURLResponse
val httpResponse = HttpResponse().apply {
statusCode = response.statusCode.toInt()
body = nsData?.bytes?.reinterpret<ByteVar>()?.toKString()
}.freeze()
result.value = httpResponse
dispatch_semaphore_signal(semaphore)
Unit
}.freeze()
val task =
NSURLSession.sharedSession.dataTaskWithRequest(nativeRequest, completionHandler)
task.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
it.resume(result.value)
}
I really want to simplified this code. Can anyone help me with it?mbonnin
07/17/2021, 5:12 PMfetch
to be suspend here as it's going to block the threadmbonnin
07/17/2021, 5:12 PMit.resume
from the completionHandler but this enters coroutine-native-mt teritorymbonnin
07/17/2021, 5:13 PMinitRuntimeIfNeeded
from the completion handleritnoles
07/17/2021, 5:41 PMsuspend fun fetch() : HttpResponse = suspendCoroutine {
val nativeRequest = NSMutableURLRequest(uRL = NSURL.URLWithString("<https://api.spacexdata.com/v4/launches>")!!)
nativeRequest.setHTTPMethod("GET")
val completionHandler = { nsData: NSData?, nsURLResponse: NSURLResponse?, nsError: NSError? ->
initRuntimeIfNeeded()
if (nsError != null) {
val message =
"The response is: " + nsURLResponse?.description() + ", error is: " + nsError.description()
println(message)
}
val response = nsURLResponse as NSHTTPURLResponse
val httpResponse = HttpResponse().apply {
statusCode = response.statusCode.toInt()
body = nsData?.bytes?.reinterpret<ByteVar>()?.toKString()
}
it.resume(httpResponse)
}.freeze()
NSURLSession.sharedSession.dataTaskWithRequest(nativeRequest, completionHandler).resume()
}
I get Uncaught Kotlin exception: kotlin.native.concurrent.FreezingException: freezing of $fetch$<anonymous>_7$FUNCTION_REFERENCE$0@c58051a8 has failed, first blocker is EventLoopImpl@c4408c68
mbonnin
07/17/2021, 5:48 PM