How can I use WearableActivity with LiveData and ViewModel

Viewed 1284

I want to be able to use the Lifecycle components from the new Android Architecture Components in my Wearable app (same as I do in my Android app).

In my main Android app I put LiveData fields in a ViewModel. This ViewModel can then be accessed/bound from both my Activity and my Fragments. To do this I use the method ViewModelProviders.of which expects either android.support.v4.app.Fragment or android.support.v4.app.FragmentActivity. So far so good...

The problem I'm facing is that my Wear app is based on the WearableActivity class which extends from android.app.Activity rather than from android.support.v4.app.FragmentActivity. This prevents me from using ViewModelProviders.of in my wearable app.

I've asked around and tried to find alternative solutions, but I don't know the internals of ViewModelProviders so I can't get around this problem right now. If there isn't an answer I hope someone who works on these components can have a look at this. It would be awesome to be able to use ViewModel & LiveData throughout my applications (mobile and wear).

4 Answers

I got it to work using AmbientMode.AmbientCallbackProvider instead of WearableActivity.

It is the new preferred method and it still gives you the onEnterAmbient(), onAmbientUpdate(), and onExitAmbient() but also lets you use Activity (or any sub classes... FragementActivity, etc.)... which allows you to support the Architecture components.

Official docs call out the details and code.

You can use this porting of architecture component: LifeCycleData

Related