in ClassyTaxiJava/app/src/main/java/com/sample/android/classytaxijava/data/DataRepository.java [64:129]
private DataRepository(final LocalDataSource localDataSource,
WebDataSource webDataSource,
BillingClientLifecycle billingClientLifecycle) {
this.localDataSource = localDataSource;
this.webDataSource = webDataSource;
this.billingClientLifecycle = billingClientLifecycle;
// Update content from the web.
// We are using a MediatorLiveData so that we can clear the data immediately
// when the subscription changes.
basicContent.addSource(webDataSource.getBasicContent(), new Observer<ContentResource>() {
@Override
public void onChanged(ContentResource contentResource) {
basicContent.postValue(contentResource);
}
});
premiumContent.addSource(webDataSource.getPremiumContent(),
new Observer<ContentResource>() {
@Override
public void onChanged(ContentResource contentResource) {
premiumContent.postValue(contentResource);
}
});
// Database changes are observed by the ViewModel.
subscriptions.addSource(localDataSource.subscriptions,
new Observer<List<SubscriptionStatus>>() {
@Override
public void onChanged(List<SubscriptionStatus> subscriptionStatuses) {
int numOfSubscriptions = subscriptionStatuses == null ?
0 : subscriptionStatuses.size();
Log.d("Repository", "Subscriptions updated: "
+ numOfSubscriptions);
subscriptions.postValue(subscriptionStatuses);
}
});
// Observed network changes are store in the database.
// The database changes will propagate to the ViewModel.
// We could write different logic to ensure that the network call completes when
// the UI component is inactive.
subscriptions.addSource(webDataSource.getSubscriptions(),
new Observer<List<SubscriptionStatus>>() {
@Override
public void onChanged(List<SubscriptionStatus> subscriptionStatuses) {
updateSubscriptionsFromNetwork(subscriptionStatuses);
}
});
// When the list of purchases changes, we need to update the subscription status
// to indicate whether the subscription is local or not. It is local if the
// the Google Play Billing APIs return a Purchase record for the SKU. It is not
// local if there is no record of the subscription on the device.
subscriptions.addSource(billingClientLifecycle.purchases, new Observer<List<Purchase>>() {
@Override
public void onChanged(List<Purchase> purchases) {
List<SubscriptionStatus> subscriptionStatuses = subscriptions.getValue();
if (subscriptionStatuses != null) {
boolean hasChanged = updateLocalPurchaseTokens(subscriptionStatuses, purchases);
if (hasChanged) {
localDataSource.updateSubscriptions(subscriptionStatuses);
}
}
}
});
}