Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate all emited streams and emit them inmidiatly with rxJava

I have a stream that emit pages of data A, B, C, D.... Which operator can I use to get a stream like this: [A], [A, B], [A, B, C], [A, B, C, D]...?

I know collect or toList but they only emit once at the end of the stream.

like image 799
Brais Gabin Avatar asked Nov 21 '25 08:11

Brais Gabin


2 Answers

You can try the 'scan' operator.

like image 145
JohnWowUs Avatar answered Nov 22 '25 22:11

JohnWowUs


Java 8

You could get a Stream of String[] in this way:

  List<String> array = Arrays.asList("A","B","C","D");
  String[] st ={""};
  Stream<String[]> stream  = array.stream().map(x -> (st[0]+=x).split("\\B"));
  //print it
  stream.forEach(s -> System.out.println(Arrays.toString(s)));

RX JAVA (expanding JohnWowUs's answer)

 List<String> array = Arrays.asList("A","B","C","D");
 Func2<String,String,String> function = new Func2<String,String,String>(){
    @Override
    public String call(String paramT1, String paramT2) {
        return paramT1 + paramT2;
    }
 };
 Observable<String> scan = Observable.from(array).scan(function);
 scan.forEach(x-> System.out.println(x));
like image 31
user6904265 Avatar answered Nov 22 '25 22:11

user6904265