0

I'm trying to purchase a packages using the Revenue Cat SDK under JetPack Compose.

The SDK provides a function called PurchasePackage() (and PurchasePackageWith()) but all of these function's signatures require an Activity which I do not know how to obtain from an @Composable.

I've tried this answer from S.O. https://stackoverflow.com/a/68423182/695524 but that gives my null as the Activity.

What does work is: val activity = LocalContext.current as Activity but, according to this answer: https://stackoverflow.com/a/65243835/695524 that is potentially unsafe to user in production code.

So, how to safely obtain an Activity from Jetpack compose so I can Purchase a Package using the Revenue Cat SDK?

DIJ
  • 347
  • 4
  • 19
  • 1
    The [answer](https://stackoverflow.com/a/68423182/695524) is correct, just replace `AppCompatActivity` with subclass of your activity, it may be `ComponentActivity` instead of `AppCompatActivity`, or something else. – Phil Dukhov Apr 19 '22 at 01:54
  • I mean superclass, not subclass. Or you just can use `Activity` instead – Phil Dukhov Apr 19 '22 at 03:24

1 Answers1

0

Thanks a lot Pylyp Dukov

Thanks to your comment, I've changed the solution to this answer: https://stackoverflow.com/a/68423182/695524 as folows:

fun Context.getActivity(): Activity? = when (this) {
    is AppCompatActivity -> this
    is ComponentActivity -> this
    is Activity -> this
    is ContextWrapper -> baseContext.getActivity()

    else -> null
}

Now, from an @Composable function, I'm able to get the/an Activity like this:

val activity = LocalContext.current.getActivity()

And now I'm able to complete a purchase with Revenue Cat.

DIJ
  • 347
  • 4
  • 19