f2prateek / rx-preferences

Reactive SharedPreferences for Android
http://f2prateek.com/2015/10/05/rx-preferences/
Apache License 2.0
1.54k stars 132 forks source link

NullPointerException when targeting devices running OS versions Android R or later #141

Open SiimKinks opened 4 years ago

SiimKinks commented 4 years ago

Looks like there has been behavior change in OnSharedPreferenceChangeListener onSharedPreferenceChanged callback when apps target devices running OS versions Android R or later. Now when preferences are cleared null key will be received in onSharedPreferenceChanged which results in app crashing due to null value being emitted to rx stream.

Please see: https://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences,%20java.lang.String)

davelogan commented 4 years ago

This is causing issues for my app as well after updating target version to 30.

Caused by: java.lang.NullPointerException: onNext called with null. Null values are generally not allowed in 2.x operators and sources. at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onNext(ObservableCreate.java:62) at com.f2prateek.rx.preferences2.RxSharedPreferences$1$1.onSharedPreferenceChanged(RxSharedPreferences.java:44) at android.app.SharedPreferencesImpl$EditorImpl.notifyListeners(SharedPreferencesImpl.java:629) at android.app.SharedPreferencesImpl$EditorImpl.lambda$notifyListeners$0$SharedPreferencesImpl$EditorImpl(SharedPreferencesImpl.java:643)

f2prateek commented 4 years ago

The easy fix here would be to add a null check here. However this would result in no notification being fired when preferences are cleared, which would be less than ideal.

I think we could also make it so that it emits the default value when this happens.

mseroczynski commented 3 years ago

@f2prateek are you still working on this?

f2prateek commented 3 years ago

I haven't worked on this - feel free to send a PR!

banasiak commented 3 years ago

@f2prateek @mseroczynski I'll try to get a PR for this with the recommend changes up sometime this week.

banasiak commented 3 years ago

I wasn't prepared to update Robolectric to support API 30, so the supplied unit test doesn't run. But, otherwise the PR in #143 fixes this in a way suggested by @f2prateek.