We will use this class to interact with the SharedPreferences class from Android by connecting the settings to RxPreferences and updating the constructor to the following:
private Settings(Context context) {
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
RxSharedPreferences rxPreferences =
RxSharedPreferences.create(preferences);
}
Finally, we will plug in a pref_keywords property from SharedPreferences to the Subjects with this:
rxPreferences.getString("pref_keywords", "").asObservable()
.filter(v -> !v.isEmpty())
.map(value -> value.split(" "))
.map(Arrays::asList)
.subscribe(keywordsSubject);
This will retrieve the monitored keywords. The following line ensures that we do not retrieve a new value when it is empty:
.filter(v -> !v.isEmpty())
This setup assumes that values are entered in one line and keywords are separated by the spaces. So, the following line splits the values and returns an array of keywords from a single text line:
.map(value -> value.split(" "))
Next, the values are converted to a list with this:
.map(Arrays::asList)
Finally, it is piped (subscribed) to the Subject by calling the following:
.subscribe(keywordsSubject);
A similar approach is taken to retrieve the financial stock symbols from the pref_symbols preference:
rxPreferences.getString("pref_symbols", "").asObservable()
.filter(v -> !v.isEmpty())
.map(String::toUpperCase)
.map(value -> value.split(" "))
.map(Arrays::asList)
.subscribe(symbolsSubject);
However, here we've added the following additional call to ensure that all symbols are uppercased:
.map(String::toUpperCase)
Finally, the entire constructor of Settings looks like this:
private Settings(Context context) {
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(context);
RxSharedPreferences rxPreferences =
RxSharedPreferences.create(preferences);
rxPreferences.getString("pref_keywords", "").asObservable()
.filter(v -> !v.isEmpty())
.map(value -> value.split(" "))
.map(Arrays::asList)
.subscribe(keywordsSubject);
rxPreferences.getString("pref_symbols", "").asObservable()
.filter(v -> !v.isEmpty())
.map(String::toUpperCase)
.map(value -> value.split(" "))
.map(Arrays::asList)
.subscribe(symbolsSubject);
}
RxSharedPreferences is now listening for changes on the pref_keywords and pref_symbols keys so that whenever the value changes there, it will be propagated to the relevant Subject.