From 494c6862937fa39fdaf118317dbf9c8fb5f0e4fa Mon Sep 17 00:00:00 2001 From: Rob X Date: Mon, 21 Aug 2023 21:54:16 +0800 Subject: [PATCH] ImageViewer, Android camera (#3487) * The camera should stop working after leaving CameraView on Android. * Update examples/imageviewer/shared/src/androidMain/kotlin/example/imageviewer/view/CameraView.android.kt --- .../example/imageviewer/view/CameraView.android.kt | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/examples/imageviewer/shared/src/androidMain/kotlin/example/imageviewer/view/CameraView.android.kt b/examples/imageviewer/shared/src/androidMain/kotlin/example/imageviewer/view/CameraView.android.kt index 4f10e50b89..00bfab8a4f 100644 --- a/examples/imageviewer/shared/src/androidMain/kotlin/example/imageviewer/view/CameraView.android.kt +++ b/examples/imageviewer/shared/src/androidMain/kotlin/example/imageviewer/view/CameraView.android.kt @@ -79,6 +79,7 @@ private fun CameraWithGrantedPermission( val context = LocalContext.current val lifecycleOwner = LocalLifecycleOwner.current val viewScope = rememberCoroutineScope() + var cameraProvider: ProcessCameraProvider? by remember { mutableStateOf(null) } val preview = Preview.Builder().build() val previewView = remember { PreviewView(context) } @@ -96,16 +97,22 @@ private fun CameraWithGrantedPermission( .build() } + DisposableEffect(Unit) { + onDispose { + cameraProvider?.unbindAll() + } + } + LaunchedEffect(isFrontCamera) { - val cameraProvider = suspendCoroutine { continuation -> + cameraProvider = suspendCoroutine { continuation -> ProcessCameraProvider.getInstance(context).also { cameraProvider -> cameraProvider.addListener({ continuation.resume(cameraProvider.get()) }, executor) } } - cameraProvider.unbindAll() - cameraProvider.bindToLifecycle( + cameraProvider?.unbindAll() + cameraProvider?.bindToLifecycle( lifecycleOwner, cameraSelector, preview,