By moving all billing logic to a BillingRepository
, which caches purchases in a local database, then serving all fragments which display ads or premium features via a BillingViewModel
, there is no need for any SharedPreferences
I can simply call:
billingViewModel = ViewModelProviders.of(this).get(BillingViewModel::class.java)
billingViewModel.userPurchasedProLiveData.observe(this, Observer {
it?.apply {
showProStatus(entitled)
}
})
private fun showProStatus(entitled: Boolean) {
if (entitled) {
btnMainMenuPro.visibility = View.GONE
disableAds()
} else {
btnMainMenuPro.visibility = View.VISIBLE
enableAds()
}
}
As per the Google Docs:
Notice that the connection to [playStoreBillingClient] is created
using the
* applicationContext. This means the instance is not [Activity]-specific. And since it's also
* not expensive, it can remain open for the life of the entire [Application]. So whether it is
* (re)created for each [Activity] or [Fragment] or is kept open for the life of the application
* is a matter of choice.
More info and an example can be found here: https://github.com/android/play-billing-samples/tree/master/TrivialDriveKotlin