Skip to content

Instantly share code, notes, and snippets.

@rascio
Last active May 15, 2018 20:43
Show Gist options
  • Save rascio/f3b4baad253dcbca07bf8400c635190a to your computer and use it in GitHub Desktop.
Save rascio/f3b4baad253dcbca07bf8400c635190a to your computer and use it in GitHub Desktop.
JavaRx parallelism
package it.r.rx;
import org.apache.commons.lang.RandomStringUtils;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
final List<String> result = Observable.from(new Integer[]{4, 5, 6, 6, 7, 3})
.doOnNext(debug("Init"))
.flatMap(i -> Observable.defer(() -> toRandomList(i)).subscribeOn(Schedulers.io()))
.doOnNext(debug("defer"))
.flatMap(Main::chooseString)
.doOnNext(debug("chooseString"))
.toList()
.doOnNext(debug("list"))
.toBlocking()
.single();
System.out.println("\nresult = " + result);
}
public static Observable<List<String>> toRandomList(Integer n) {
debug("perform IO").call(n);
try {
Thread.sleep(new Random().nextInt(3000));
} catch (InterruptedException e) {
e.printStackTrace();
}
debug("IO done").call(n);
final List<String> result = Stream.iterate(0, t -> t + 1)
.map(i -> RandomStringUtils.randomAlphanumeric(n))
.limit(n)
.collect(Collectors.toList());
return Observable.just(result);
}
public static Observable<String> chooseString(List<String> list) {
if (Math.random() > .3) {
return Observable.just(list.get(new Random().nextInt(list.size())));
}
else {
return Observable.empty();
}
}
public static <T> Action1<T> debug(String s) {
return o -> System.out.println(o + " | " + s + " | " + Thread.currentThread().getName());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment