Android Architecture Components - ViewModel Observable & Proguard
Asked Answered
Q

1

7

I'm having trouble getting the ViewModel component to work with Proguard. I already had to add the following to prevent a crash due to NoSuchMethodException: init()

-keep class com....SlideshowViewModel {*;}

However, my observers in the activity aren't receiving any data. This works fine until I enable Proguard, so I know Proguard is the reason, I just don't know why (novice Proguardian here). What rule do I need to add to make the observables work?

I have the following in my ViewModel (Kotlin)

val currentItem = MediatorLiveData<MediaItem>()

....later...

        Timber.d("Setting next image: " + position + " out of " + mediaItemList.size)
        currentItem.value = mediaItemList[position]

and the Activity (Java)

    viewModel.getCurrentItem().observe(this, new Observer<MediaItem>() {
        @Override
        public void onChanged(@Nullable final MediaItem mediaItem) {
            Timber.d("Activity received new item");
        }
    });

In the log I receive: D/SlideshowViewModel: Setting next image: 0 out of 18

But nothing get's fired in the onChanged Observable.

Quillen answered 27/6, 2017 at 0:23 Comment(0)
Q
10

Found it on: https://issuetracker.google.com/issues/62113696

It should be fixed soon though (not in alpha3 yet)

## Android architecture components: Lifecycle
# LifecycleObserver's empty constructor is considered to be unused by proguard
-keepclassmembers class * implements android.arch.lifecycle.LifecycleObserver {
    <init>(...);
}
# ViewModel's empty constructor is considered to be unused by proguard
-keepclassmembers class * extends android.arch.lifecycle.ViewModel {
    <init>(...);
}
# keep Lifecycle State and Event enums values
-keepclassmembers class android.arch.lifecycle.Lifecycle$State { *; }
-keepclassmembers class android.arch.lifecycle.Lifecycle$Event { *; }
# keep methods annotated with @OnLifecycleEvent even if they seem to be unused
# (Mostly for LiveData.LifecycleBoundObserver.onStateChange(), but who knows)
-keepclassmembers class * {
    @android.arch.lifecycle.OnLifecycleEvent *;
}
Quillen answered 27/6, 2017 at 0:50 Comment(1)
In newer versions it seems like it should be enough to ignore the notes, e.g.: -dontnote android.arch.lifecycle.**Hamnet

© 2022 - 2024 — McMap. All rights reserved.