Calling onResume() from your ViewModel in Android.
Tags: android, kotlin, mobile, tristan
Published: 2023-03-30 23:15:33

### Table of contents
1. [The problem I am solving](#prob)
2. [Solution](#sol)
3. [Lifecycle observer](#ob)
4. [LifecycleOwner](#own)
5. [Making it work](#work)
6. [Removing the observer](#re)

### My app on the Google Playstore
- [HERE](https://play.google.com/store/apps/details?id=com.elliottsoftware.calftracker)

### GitHub code <a name="github"></a>
- [HERE](https://github.com/thePlebDev/CalfTracker)


### The problem I am trying to solve <a name="prob"></a>
- So as I am integrating a subscription into my Android app, there is a particular line of the documentation that stands out when talking about [Fetching Purchases]():

`To handle these situations, be sure that your app calls BillingClient.queryPurchasesAsync() in your onResume() method to ensure that all purchases are successfully processed as described in processing purchases.`

- Which brings up the problem of , `how and where do I call the onResume() method`.

### The solution <a name="sol"></a>
- The two main ways I have discovered to handle this are:

**1) Side-effect :** using [DisposableEffect](https://developer.android.com/jetpack/compose/side-effects#disposableeffect) to call `onResume()` in your compose code

**2) Lifecycle observer :** creating a [DefaultLifecycleObserver](https://developer.android.com/topic/libraries/architecture/lifecycle#lc) to call `onResume()` inside of my ViewModel (I chose this version)


### 2) Lifecycle observer <a name="ob"></a>
- Now when we say we are going to create a `Lifecycle observer`, we are saying we are creating a class that will observe the Android lifecycle of a certain component(like Activity of Fragment). There are two parts to a lifecycle observer, `1) the lifecycle  observer` and `2) the lifecycle owner`.

- In order to create a Lifecycle observer we need to have a class implement the  [DefaultLifecycleObserver](https://developer.android.com/reference/androidx/lifecycle/DefaultLifecycleObserver) interface, like so:
```
class BillingViewModel(): ViewModel(),DefaultLifecycleObserver {

 override fun onResume(owner: LifecycleOwner) {
       // do whatever you want
       refreshPurchases()
    }
}

```
- By implementing the `DefaultLifecycleObserver` we have given our ViewModel access to a `LifecycleOwner's` methods like `onResume()` and the Android library will now recognize instances of `BillingViewModel` as a Lifecycle observer.

- But now we need to attach our Lifecycle observer to a LifecycleOwner


### LifecycleOwner <a name="own"></a>
- A class is considered a LifecycleOwner if it implements the [LifecycleOwner](https://developer.android.com/reference/androidx/lifecycle/LifecycleOwner) interface. In my code I am using Fragments and according to the documentation [Fragment](https://developer.android.com/reference/androidx/fragment/app/Fragment.html) implements a LifecycleOwner interface.

- So now that we have a LifecycleOwner (Fragment) and a LifecycleObserver(BillingViewmodel) we need to attach them.

### Making it work  <a name="work"></a>
- So inside my Fragment looks something like this:
```
class SubscriptionFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {



        val billingViewModel:BillingViewModel by viewModels()

        // THIS IS WHERE WE ARE CONNECTING THE TWO
        lifecycle.addObserver(billingViewModel)

   }

```

- The code that adds the observer to the owner is `lifecycle.addObserver(billingViewModel)`. Which now gives our ViewModel access to the Fragment's lifecycle methods

- I would also like to point out, `viewModels()` means that this particular ViewModel will be scoped to the closes `ViewModelStoreOwner` which in my case is the fragment. If you want to read more about ViewModel scoping I would recommend [THIS](https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-apis) resource 

- The term `scoped/scoping` means that the ViewModel will live as long as the item it is scoped to


### Removing the observer <a name="re"></a>
- You might of noticed that I have not removed the observer... curious right? I have even read tutorials like, this one [HERE](https://betterprogramming.pub/empowered-lifecycle-aware-viewmodel-for-android-f495de9a8170), removing the observer. However, I found [This](https://developer.android.com/reference/androidx/lifecycle/LiveData#observeForever(androidx.lifecycle.Observer%3C?%20super%20T%3E)) section of documentation stating:

 `An observer added with a Lifecycle will be automatically removed if the corresponding Lifecycle moves to DESTROYED state.`

- So I have decided to not remove the observer manually and let the Android system handle it.

### Conclusion
- Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on [Twitter](https://twitter.com/AndroidTristan).