androidandroid-jetpack-composeandroid-pay

Jetpack compose listing for onActivityResult (Google Wallet Integration)


I started to add Add to Google wallet functionality to my compose App, when doing the push provision tokenisation , I'm stuck since they're still using the deprecated onActivityResult instead of the new contract api.

PushTokenizeRequest pushTokenizeRequest = new PushTokenizeRequest.Builder()
    .setOpaquePaymentCard(opc)
    .setNetwork(cardNetwork)
    .setTokenServiceProvider(tokenProvider)
    .setDisplayName("My Card")
    .setLastDigits("1234")
    .setUserAddress(userAddress)
    .build();

tapAndPayClient.pushTokenize(
    activity, // here i'm passing my current activity. 
    pushTokenizeRequest,
    REQUEST_CODE_PUSH_TOKENIZE); 

Documentation says to implement this method on Activity, But i'm not sure how to get this value to my composeScreen.

Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == REQUEST_CODE_PUSH_TOKENIZE) {
    if (resultCode == RESULT_CANCELED) {
      // TODO: Handle provisioning failure here.
      return;
    } else if (resultCode == RESULT_OK) {
      // TODO: Handle successful provisioning here.
      String tokenId = data.getStringExtra(TapAndPay.EXTRA_ISSUER_TOKEN_ID);
      return;
    }
  }
  // TODO: Handle results for other request codes.
  // ...
}

Solution

  • You just need to create a state-tracking variable in your ViewModel, and update it when onActivityResult() is triggered. And in your Composable, observe that variable for changes. Something like this:

    In your ViewModel:

    var walletResult = MutableLiveData(0)
    

    In onActivityResult():

    if (resultCode == RESULT_CANCELED) {
        viewModel.walletResult.postVlue(-1)
    } else if (resultCode == RESULT_OK) {
        viewModel.walletResult.postVlue(1)
    }
    

    And in your Composable:

    val walletResult by viewModel.walletResult.observeAsState(0)
    LaunchedEffect(walletResult){
        if(walletResult > 0){
            // trigger positive response notification
        }else if(walletResult < 0){
            // trigger negative response notification
        }
        
        // reset the value back to neutral
        viewModel.walletResult.postVlue(0)
    }