'I would suggest not to make a Singleton class that provides BillingClient from it and initialized through application class.'
Why? Because, in doing such way, you've chance to leak memory or object while using throughout app.
Alternate way is to make such class as LifecycleObserver, so that once you bind it to your Activity/Fragment though respects it's lifecycle and do stuffs accordingly.
I've created such class as below and using in some of my projects (In which, it's working pretty well).
Check out the class below :
InAppBilling.kt
class InAppBilling(val lifecycle: Lifecycle, purchasesUpdatedListener: PurchasesUpdatedListener) :
LifecycleObserver,
PurchasesUpdatedListener by purchasesUpdatedListener,
BillingClientStateListener {
companion object {
const val TAG = "InAppBilling"
}
init {
lifecycle.addObserver(this)
}
private var mBillingClient: BillingClient? = null
private fun initClient(): BillingClient {
return BillingClient
.newBuilder(context) // You can provide application context here.
.setListener(this)
.build()
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_CREATE)
fun connectionToBillingServer() {
mBillingClient = initClient()
mBillingClient?.startConnection(this)
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_DESTROY)
fun disconnectFromBillingServer() {
mBillingClient?.endConnection()
lifecycle.removeObserver(this)
}
override fun onBillingServiceDisconnected() {
if (lifecycle.currentState == Lifecycle.State.CREATED) {
mBillingClient?.startConnection(this)
}
}
override fun onBillingSetupFinished(responseCode: Int) {
// Left out because "Unused"
}
}
And how to consume it :
Inside of your Activity/Fragment where you want to use BillingClient:
private var mBillingClient: InAppBilling? = null
//.. And inside of onCreate() method, you'll just need to initialize it like below:
mBillingClient = InAppBilling(this@Activity.lifecycle, this)
Now, you can use this billingClient object to do stuffs that you want from In-App client.
All you'll need to do is to add your specific method to InAppBilling class and consume that method where you wanted it.
Check out the same class from this gist.