```suspend fun fetch() : HttpResponse = suspendCor...
# kotlin-native
i
Copy code
suspend 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?
m
Not sure you can do much better if you want a blocking HTTP call. Note that I don't think you need
fetch
to be suspend here as it's going to block the thread
You could also call
it.resume
from the completionHandler but this enters coroutine-native-mt teritory
Also you should call
initRuntimeIfNeeded
from the completion handler
i
I tried with org.jetbrains.kotlinxkotlinx coroutines core1.5.1-native-mt
Copy code
suspend 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
m
Yea that stuff is complex. I'm not 100% sure what can and cannot be freezed with coroutine-mt