0
\$\begingroup\$

I am using RxJava with retrofit to get data from an API then filtering the data with a for loop in the onNext Method. Is there any way not to use the for loop and just use RxJava to filter or improve the code?

 _subscriptions.add(
 jamSpeakServiceApi.getAllWords()
 .subscribeOn(Schedulers.io())
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(new Observer<List<WordApi>>() {
 @Override
 public void onCompleted() {
 Log.d("retroffit Completed", "Completed");
 }
 @Override
 public void onError(Throwable e) {
 Log.d("retroffit error", e.toString());
 }
 @Override
 public void onNext(List<WordApi> wordApis) {
 /*Observable.from(wordApis)
 .filter(s -> Word.getWordFormDatabase(s.getWord()) != null)
 .filter(s -> s.getCountry().toLowerCase().equals("jamaica"))
 .filter(s -> Word.getWordLikeFormDatabase(s.getWord()) != null)
 .subscribe();*/
 for (WordApi x: wordApis){
 if(x.getCountry().toLowerCase().equals("jamaica")== true){
 Word.saveWordFromApi(x);
 Log.d(x.getWord(),x.getWord());
 }
 }
 }
 })
 );
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Apr 29, 2016 at 16:14
\$\endgroup\$
1

1 Answer 1

3
\$\begingroup\$

You should use flat to emit each wordApi and then you will be able to filter your data and apply your function one by one.

Your stream should look like this:

jamSpeakServiceApi.getAllWords()
 .subscribeOn(Schedulers.io())
 .flatMap(wordApis -> Observable.from(wordApis))
 .filter(wordApi -> wordApi.getCountry().toLowerCase().equals("jamaica"))
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(new Observer<WordApi>() {
 @Override
 public void onCompleted() {
 Log.d("retroffit Completed", "Completed");
 }
 @Override
 public void onError(Throwable e) {
 Log.d("retroffit error", e.toString());
 }
 @Override
 public void onNext(WordApi wordApi) {
 Word.saveWordFromApi(wordApi);
 Log.d(wordApi.getWord(),wordApi.getWord());
 }
 })

I used some lambdas, and I recommend you to use them too. Take a look at the Retrolambda Gradle plugin. It works well with an Android environment.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Jun 7, 2016 at 23:34
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.