'Thread freezes when trying to wait for callback

i am trying to interrupt a for-loop with a endless running while-loop till the Callback onSuccess changes the condition and the while-loop is exited, like so:

for(distance in FocusDistances){
                settingFocus = true
                Log.d(TAG, "setting focus to $distance")
                var captureRequestOptions = CaptureRequestOptions.Builder()
                    .setCaptureRequestOption(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF)
                    .setCaptureRequestOption(CaptureRequest.LENS_FOCUS_DISTANCE, distance).build()

                Camera2CameraControl.from(camera!!.cameraControl).captureRequestOptions =
                    captureRequestOptions

                var listenableFuture = Camera2CameraControl.from(camera!!.cameraControl)
                    .setCaptureRequestOptions(captureRequestOptions)
                Futures.addCallback(listenableFuture, object : FutureCallback<Void> {
                    override fun onSuccess(result: Void?) {
                        settingFocus = false
                        captureImage(imageCapture)
                        Log.d(TAG, "focus set!")
                    }

                    override fun onFailure(t: Throwable?) {
                        Log.e(TAG, "Failed setting Focus ${t!!.message}")
                    }
                }, context!!.mainExecutor)

                while(settingFocus){
                    continue
                }
            }
        }

My problem is that while-loop starts befor the callback is able to complete and when the while-loop is running everything freezes and nothing else is executed. i dont get any callback back and that loop runs for ever.

Could someone give me some advise how to correct this ?

My actual goal is to take a number of pictures at differnt focal length. for that i want to set focus, when focus set a picture should be taken and only when the picture gets saved it should continue with the next picture at a different focal length.

thanks in advance



Solution 1:[1]

The appropriate approach is to use ListenableFuture.await().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis Wasserman