0

I have a listener where the user can send a POST HTTP request, but I want to let the user send as many HTTP requests as possible (He won't have to wait for the HTTP request to end), but I am not sure about whether to use Coroutines or threads. So I need to be pointed into documentation that provides a context for what I want to do. Here is my code, where the target function to run in a thread is uploadFile:

            ...
            findViewById<View>(R.id.screen).setOnClickListener { _: View? ->
            imgCap.takePicture(object : ImageCapture.OnImageCapturedListener() {
                override fun onCaptureSuccess(image: ImageProxy, rotationDegrees: Int) {
                    i += 1;
                    Log.i("Click", "Click number $i");
                    Toast.makeText(baseContext, "Image Captured", Toast.LENGTH_SHORT).show()
                    uploadFile(image)
                    super.onCaptureSuccess(image, rotationDegrees)
                }
            })
        }
        CameraX.bindToLifecycle(this, preview, imgCap)
    }
    private fun uploadFile(img: ImageProxy) {
        val url = "https://5d6d-41-97-171-237.eu.ngrok.io/api/photos"
        val bitmap = img.convertImageProxyToBitmap()
        Log.e("bitmap", bitmap.toString())
        val imgBase = convertImageToBase64(bitmap)

        val bos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, bos)


        // add parameter
        val formBody = FormBody.Builder().add("photo", imgBase).build()


        // creating request
        var request = Request.Builder().url(url)
            .post(formBody)
            .build()

        var client = OkHttpClient();
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                println(response.body?.string())

            }

            override fun onFailure(call: Call, e: IOException) {
                Log.e("Exception:", e.toString())
                Log.e("Error:", e.message.toString())
            }
        })
    }
1

2 Answers 2

2

Kotlin Coroutines can be used for that:

// making function `suspend` to suspend a coroutine 
// and execute other code after that if need
private suspend fun uploadFile(img: ImageProxy) = suspendCoroutine { continuation ->
    // ... initialize request

    var client = OkHttpClient();
    client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                println(response.body?.string())
                continuation.resume(response) // resumes the coroutine
            }
    
            override fun onFailure(call: Call, e: IOException) {
                Log.e("Exception:", e.toString())
                Log.e("Error:", e.message.toString())
                continuation.resume(null)    // resumes the coroutine
                // or continuation.resumeWithException(e)
            }
        })
}

// call this function instead of `uploadFile()`
private fun upload(img: ImageProxy) {
    // launch-and-forget coroutine
    lifecycleScope.launch {
        uploadFile(img)
        // do something after file is uploaded
    }
}

suspendCoroutine builder was used here to convert an api function with callback into a suspend function.

Sign up to request clarification or add additional context in comments.

Comments

0

After delving into more into the application, I had to set a lower resolution on the ImageCaptureConfig builder with setTargetResolution(resolution).

I started doing multiple requests at the same time, and it seems that the Event Listener on the view is acting asynchronously, managing to perform a request after a request without waiting for the first request to finish uploading the file. There are some limitations, and that's due to hardware that I'm looking into. But the code I was using works perfectly as I wanted to after I was able to notice uploads on shorter timescales.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.