private List mergeSubscriptionsAndPurchases()

in ClassyTaxiJava/app/src/main/java/com/sample/android/classytaxijava/data/DataRepository.java [225:270]


    private List<SubscriptionStatus> mergeSubscriptionsAndPurchases(
            @Nullable List<SubscriptionStatus> oldSubscriptions,
            @Nullable List<SubscriptionStatus> newSubscriptions,
            @Nullable List<Purchase> purchases) {
        List<SubscriptionStatus> subscriptionStatuses = new ArrayList<>();
        if (purchases != null) {
            // Record which purchases are local and can be managed on this device.
            updateLocalPurchaseTokens(newSubscriptions, purchases);
        }
        if (newSubscriptions != null) {
            subscriptionStatuses.addAll(newSubscriptions);
        }
        // Find old subscriptions that are in purchases but not in new subscriptions.
        if (purchases != null && oldSubscriptions != null) {
            for (SubscriptionStatus oldSubscription : oldSubscriptions) {
                if (oldSubscription.isSubAlreadyOwned() && oldSubscription.isLocalPurchase()) {
                    // This old subscription was previously marked as "already owned" by
                    // another user. It should be included in the output if the SKU
                    // and purchase token match their previous value.
                    for (Purchase purchase : purchases) {
                        if (purchase.getSkus().get(0).equals(oldSubscription.getSku()) &&
                                purchase.getPurchaseToken().equals(oldSubscription.getPurchaseToken())) {
                            // The old subscription that was already owned subscription should
                            // be added to the new subscriptions.
                            // Look through the new subscriptions to see if it is there.
                            boolean foundNewSubscription = false;
                            if (newSubscriptions != null) {
                                for (SubscriptionStatus newSubscription : newSubscriptions) {
                                    if (TextUtils.equals(newSubscription.getSku(),
                                            oldSubscription.getSku())) {
                                        foundNewSubscription = true;
                                    }
                                }
                            }
                            if (!foundNewSubscription) {
                                // The old subscription should be added to the output.
                                // It matches a local purchase.
                                subscriptionStatuses.add(oldSubscription);
                            }
                        }
                    }
                }
            }
        }
        return subscriptionStatuses;
    }