Untitled

mail@pastecode.io avatar
unknown
java
3 years ago
1.7 kB
4
Indexable
Never
package com.cantire.pricing.apigateway.netprices;

import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleOnSubscribe;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * @author Yevhen_Voroniuk
 */
public class RxJavaTest {
  public static void main(String[] args) {
    var firstCall = Single.create((SingleOnSubscribe<String>) emitter -> {
      sleep(1000);
      emitter.onSuccess("Hello");
    });
    var secondCall = Single.create((SingleOnSubscribe<Integer>) emitter -> {
      sleep(1500);
      emitter.onSuccess(42);
    });

    long start = System.nanoTime();
    var firstCombinedCall =
        Single.zip(
            firstCall.subscribeOn(Schedulers.io()),
            secondCall.subscribeOn(Schedulers.io()),
            (s, integer) -> s + integer.toString());

    var thirdCall = Single.create((SingleOnSubscribe<String>) emitter -> {
      sleep(500);
      emitter.onSuccess(" World");
    });
    var secondCombinedCall =
        Single.zip(
            firstCombinedCall.subscribeOn(Schedulers.io()),
            thirdCall.subscribeOn(Schedulers.io()),
            (s1, s2) -> s1 + s2);

    var res = secondCombinedCall.blockingGet();
    System.out.println(res);
    printCurrentTime("Execution time", start);
  }

  public static void sleep(long millis) {
    try {
      Thread.sleep(millis);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  private static void printCurrentTime(String text, long startNanos) {
    long time = (System.nanoTime() - startNanos) / 1000000;
    System.out.println(text + ": " + time + "ms");
  }
}