I had the same problem and after 2 days of brainstorming I found an updated solution.
In my case I'm using Navigation Component, that is, I have a MainActivity as a container for the fragments.
The magic solution is quite simple actually:
Create a ViewModel and declare the BillingClient object, like this:
class BillingViewModel : ViewModel() {
var billingClient: BillingClient? = null
}
In the MainActivity, declare the ViewModel, create an instance of BillingClient in the onCreate() method, and pass this value to the ViewModel's billingClient object, like this:
class MainActivity : AppCompatActivity() {
private val viewModel by viewModels<BillingViewModel>()
private var billingClient: BillingClient? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
billingClient = BillingClient.newBuilder(applicationContext)
.setListener(MyPurchasesUpdatedListener(this, this))
.enablePendingPurchases()
.build()
viewModel.billingClient = billingClient
}
}
Okay, now you can get that same instance in any fragment you need it.
But there is one last important thing for you to consider, pay attention:
When declaring the ViewModel in some fragment, do it this way:
class YourFragment : Fragment() {
private val viewModel by activityViewModels<BillingViewModel>()
private var billingClient: BillingClient? = null
}
It is very important that you use "activityViewModels()" to declare the ViewModel, do not confuse it with "viewModels()", there is a difference here. Using "activityViewModels()" you guarantee that you are accessing the same BillingClient instance that was initialized in the MainActivity.
Now, just pass the billingClient value from the viewModel to the billingClient object from your fragment in onCreateView, like this:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
billingClient = viewModel.billingClient
}
BillingClient.endConnection
, right? Is that safe? It seems like it might be safe, because the connection should safely disconnect when the app terminates, but I can't tell for sure. – Repeater