简体   繁体   中英

Not Getting result from rememberLauncherForActivityResult() in jetpack compose

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}")
        }

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 eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM