@CheckReturnValue
  @NonNull public static Observable<Boolean> observePowerSavingState(
      @NonNull Context context, @StringRes int enablePrefResId, @BoolRes int defaultValueResId) {
    final RxSharedPrefs prefs = AnyApplication.prefs(context);
    return Observable.combineLatest(
            prefs
                .getString(
                    R.string.settings_key_power_save_mode,
                    R.string.settings_default_power_save_mode_value)
                .asObservable(),
            enablePrefResId == 0
                ? Observable.just(true)
                : prefs.getBoolean(enablePrefResId, defaultValueResId).asObservable(),
            RxBroadcastReceivers.fromIntentFilter(
                    context.getApplicationContext(), getBatteryStateIntentFilter())
                .startWith(new Intent(Intent.ACTION_BATTERY_OKAY)),
            RxBroadcastReceivers.fromIntentFilter(
                    context.getApplicationContext(), getChargerStateIntentFilter())
                .startWith(new Intent(Intent.ACTION_POWER_DISCONNECTED)),
            getOsPowerSavingStateObservable(context),
            (powerSavingPref, enabledPref, batteryIntent, chargerIntent, osPowerSavingState) -> {
              if (!enabledPref) return false;

              switch (powerSavingPref) {
                case "never":
                  return false;
                case "always":
                  return true;
                default:
                  return osPowerSavingState
                      || (Intent.ACTION_BATTERY_LOW.equals(batteryIntent.getAction())
                          && Intent.ACTION_POWER_DISCONNECTED.equals(chargerIntent.getAction()));
              }
            })
        .distinctUntilChanged();
  }
@Test
  public void testControlledByEnabledPrefDefaultFalse() {
    AtomicReference<Boolean> state = new AtomicReference<>(null);
    final Observable<Boolean> powerSavingState =
        PowerSaving.observePowerSavingState(
            getApplicationContext(),
            settings_key_power_save_mode_sound_control,
            settings_default_false);
    Assert.assertNull(state.get());

    final Disposable disposable = powerSavingState.subscribe(state::set);
    // starts as false
    Assert.assertEquals(Boolean.FALSE, state.get());

    sendBatteryState(false);
    Assert.assertEquals(Boolean.FALSE, state.get());

    sendBatteryState(true);
    Assert.assertEquals(Boolean.FALSE, state.get());

    SharedPrefsHelper.setPrefsValue(R.string.settings_key_power_save_mode_sound_control, true);

    Assert.assertEquals(Boolean.TRUE, state.get());
    sendBatteryState(false);
    Assert.assertEquals(Boolean.FALSE, state.get());
    sendBatteryState(true);
    Assert.assertEquals(Boolean.TRUE, state.get());
    sendBatteryState(false);
    Assert.assertEquals(Boolean.FALSE, state.get());

    disposable.dispose();
  }