Operator – rxjava returns the subscribed value in the function

For some reason, I sometimes want to use RX operators instead of the normal Java way to convert data structures, because it is cleaner and cleaner For example:

Observable.from(listOfStrings)
.filter(string -> string.getNumber() >5)
.toList()

Is there any way to wait for the observable result and return it in the function: do this (but it doesn't work):

private String getFilteredString(String string){
   Observable.from(listOfStrings)
       .filter(string -> string.getNumber() >5)
       .toList()
       .subscribe(finalStirng -> {
       return finalString;
       })
}

Solution

You can use Toblocking() converts any observable to synchronous observable:

private List<String> getFilteredString(List<String> strings) {
  return Observable.from(strings)
      .filter(string -> string.length() > 5)
      .toList()
      .toBlocking()
      .single();
}

Update: Although the above code is completely valid and works as expected, this is not the way rxjava is used If your only goal is to transform collections, there are better ways:

>Java 8 has a stream API > guava has its own collections API > Apache has a Commons collections library

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>