没有从 jetpack compose 中的 rememberLauncherForActivityResult() 获取结果

Posted

技术标签:

【中文标题】没有从 jetpack compose 中的 rememberLauncherForActivityResult() 获取结果【英文标题】:Not Getting result from rememberLauncherForActivityResult() in jetpack compose 【发布时间】:2021-10-18 09:26:52 【问题描述】:

我正在打电话给StartIntentSenderForResult(),但它没有被调用。

    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】:

如果有人遇到同样的问题,那么只需使用这个可组合的而不是 rememberLauncherForActivityResult()

感谢@Róbert Nagy 参考:https://***.com/a/65323208/15301088

我从原始帖子中删除了一些不推荐使用的代码,现在它对我来说很好。

@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

例如

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


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

【讨论】:

代码中的 realLauncher 变量在哪里?

以上是关于没有从 jetpack compose 中的 rememberLauncherForActivityResult() 获取结果的主要内容,如果未能解决你的问题,请参考以下文章

Jetpack Compose 从入门到入门

Jetpack Compose 从入门到入门

Jetpack Compose 从入门到入门

Jetpack Compose 从入门到入门

Jetpack Compose 中的重组作用域和性能优化

如何从 Jetpack Compose 中的 URL 加载图像? [复制]