Created
March 22, 2016 19:04
-
-
Save rodrigohenriques/7af75bef742cad6f84f3 to your computer and use it in GitHub Desktop.
Testing asyncronous observables to parallelize work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SampleTest { | |
@Test | |
public void testObservableParallel() { | |
List<String> terminals = new ArrayList<>(); | |
for (int i = 0; i < 100000; i++) { | |
terminals.add(i, String.format("Terminal %s", i + 1)); | |
} | |
PublishSubject<String> publisher = PublishSubject.create(); | |
long start = System.currentTimeMillis(); | |
publisher.subscribe(id -> { | |
System.out.print("Result: " + id); | |
System.out.println(" Thread: " + Thread.currentThread()); | |
}, error -> {}, () -> { | |
final long executionTime = System.currentTimeMillis() - start; | |
System.out.println(String.format("Execution time: %s", executionTime)); | |
}); | |
Observable.from(terminals) | |
.subscribe(terminalId -> | |
Observable.just(terminalId) | |
.subscribeOn(Schedulers.computation()) | |
.subscribe(publisher::onNext), error -> {}, publisher::onCompleted); | |
} | |
@Test | |
public void testObservableSerial() { | |
List<String> terminals = new ArrayList<>(); | |
for (int i = 0; i < 100000; i++) { | |
terminals.add(i, String.format("Terminal %s", i + 1)); | |
} | |
long start = System.currentTimeMillis(); | |
Observable.from(terminals) | |
.subscribe(terminalId -> { | |
System.out.print("Result: " + terminalId); | |
System.out.println(" Thread: " + Thread.currentThread()); | |
}, error -> {}, () -> { | |
final long executionTime = System.currentTimeMillis() - start; | |
System.out.println(String.format("Execution time: %s", executionTime)); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment