Not Getting result from rememberLauncherForActivityResult() in jetpack compose

Viewed 792

I'm calling StartIntentSenderForResult() but it doesn't get called.

    val authResult = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartIntentSenderForResult()
    ) {
        Log.d("appDebug", "called!!!") // not get called
    }

    oneTapClient.beginSignIn(signUpRequest)
        .addOnSuccessListener(activity) { result ->
            try {
                // Calling here for result
                authResult.launch(
                    IntentSenderRequest
                        .Builder(result.pendingIntent.intentSender)
                        .build()
                )
            } catch (e: IntentSender.SendIntentException) {
                Log.d("appDebug", "CATCH : ${e.localizedMessage}")
            }
        }
        .addOnFailureListener(activity) { e ->
            Log.d("appDebug", "FAILED : ${e.localizedMessage}")
        }
1 Answers

If someone having same issue then just use this composable instead of rememberLauncherForActivityResult().

Thanks to @Róbert Nagy Ref: https://stackoverflow.com/a/65323208/15301088

I removed some deprecated codes from original post now it works fine for me.

@Composable
fun <I, O> registerForActivityResult(
    contract: ActivityResultContract<I, O>,
    onResult: (O) -> Unit
): ActivityResultLauncher<I> {
    val owner = LocalContext.current as ActivityResultRegistryOwner
    val activityResultRegistry = owner.activityResultRegistry

    // Tracking current onResult listener
    val currentOnResult = rememberUpdatedState(onResult)

    // Only need to be unique and consistent across configuration changes.
    val key = remember { UUID.randomUUID().toString() }

    DisposableEffect(activityResultRegistry, key, contract) {
       onDispose {
           realLauncher.unregister()
       }
   }

   return realLauncher
}

for e.g.

val registerActivityResult = registerForActivityResult(
    contract = ActivityResultContracts.StartIntentSenderForResult()
) {
    // handle your response
}

// just call launch and pass the contract
registerActivityResult.launch(/*Your Contract*/)
Related