Random rand = new Random();
Observable<Integer> random1 = Observable.just(rand.nextInt());
Observable<Integer> random2 = random1.flatMap(r1->Observable.just(r1 * rand.nextInt()));
random2.subscribe(System.out::println);
The above code is just taking a couple of random numbers, multiplying them together, and printing the output.
Here's my question: At the time that I print out the result, is there an elegant way I can get hold of the first random value? Please note that my actual system is making asynchronous calls, not just producing random numbers.
Here are some examples of what I would not consider elegant:
Random rand = new Random();
Observable<Integer> random1 = Observable.just(rand.nextInt());
random1.subscribe(r1->{
Observable<Integer> random2 = Observable.just(r1 * rand.nextInt());
random2.subscribe(r2->{
System.out.println(r1);
System.out.println(r2);
});
});
.
Random rand = new Random();
Observable<Integer> random1 = Observable.just(rand.nextInt());
Observable<int[]> result = random1.flatMap(r1->{
int[] pair = new int[2];
pair[0] = r1;
pair[1] = r1 * rand.nextInt();
return Observable.just(pair);
});
result.subscribe(pair-> {
System.out.println(pair[0]);
System.out.println(pair[1]);
});
.
Random rand = new Random();
int[] hack = new int[1];
Observable<Integer> random1 = Observable.just(rand.nextInt()).doOnNext(r1->hack[0]=r1);
Observable<Integer> random2 = random1.flatMap(r1->Observable.just(r1 * rand.nextInt()));
random2.subscribe(r2->{
System.out.println(hack[0]);
System.out.println(r2);
});
And, finally, there's this, which I'm not sure is good practice:
Random rand = new Random();
Observable<Integer> random1 = Observable.just(rand.nextInt());
Observable<Integer> random2 = random1.flatMap(r1->Observable.just(r1 * rand.nextInt()));
random2.subscribe(r2-> System.out.println(random1.toBlocking().first()));