Creating a Preview for a Composable that takes Google Billing API information such as a `ProductDetail`

66 Views Asked by At

Consider a Composable screen with the following parameters:

@Composable
fun PurchaseSubscriptionScreenContent(
    availableSubscriptions: List<ProductDetails>,
    selectedSubscription: ProductDetails,
    isLoading: Boolean,
    onPurchaseClicked: () -> Unit,
) {...}

I would like to write a Preview for this screen, but the init for ProductDetails is private, and the following error is shown when this is attempted:

Cannot access '<init>': it is package-private in 'ProductDetails'

I do not wish to use the Google Billing API in the preview as this would involve using an internet connection. How would I best write a Preview for this composable, given these parameters?

The only approach I could think of so far is to just use more basic types and do the mapping from ProductDetails myself? e.g:

@Composable
fun PurchaseSubscriptionScreen(productDetails: List<ProductDetail>) {
    PurchaseSubscriptionScreenContent(
        subscritpionNames = productDetails.map { it.name },
        subscritpionDescriptions = productDetails.map { it.description },
        ...
    )
}

@Composable
fun PurchaseSubscriptionScreenContent(
    subscriptionNames: List<String>,
    subscriptionDescritpions: List<String>,
    subscriptionOfferDesceritpions: List<String>,
    ...
    isLoading: Boolean,
    onPurchaseClicked: () -> Unit,
) {...}

It is perfectly reasonable to do this mapping in a view model too so that it is testable but it just feels a little annoying to be re-creating the ProductDetail object from scratch? Any other ideas are welcome.

1

There are 1 best solutions below

0
On BEST ANSWER

Definitely create a custom class like a Product with proper mapping methods. Then just use it in your business logic, view models and Composables. View should not be aware of the library used. This way, apart from Preview and testability, you protect your code from Billing library changes.