Brais Gabin
Brais Gabin

Reputation: 5935

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.

Upvotes: 3

Views: 473

Answers (3)

Lubo
Lubo

Reputation: 1827

Flux (project reactor) version:

public class Main {
    public static void main(String[] args) throws InterruptedException {
        final Flux<Double> randomChange = Flux.interval(Duration.ofMillis(75))
                .map(i -> Math.random() - 0.5);

        final Flux<Double> stockCurrentValue = randomChange.scan(100.0, (x, y) -> x + y);

        stockCurrentValue
                .takeWhile(stockValue -> stockValue > 90 && stockValue < 110)
                .subscribe(x -> System.out.println(x));

        Thread.sleep(100000);
    }
}

Upvotes: 0

user6904265
user6904265

Reputation: 1938

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));

Upvotes: 1

JohnWowUs
JohnWowUs

Reputation: 3083

You can try the 'scan' operator.

Upvotes: 5

Related Questions