io.reactivex.plugins.RxJavaPlugins Java Examples

The following examples show how to use io.reactivex.plugins.RxJavaPlugins. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SampleApplication.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    rxBleClient = RxBleClient.create(this);
    RxBleClient.updateLogOptions(new LogOptions.Builder()
            .setLogLevel(LogConstants.INFO)
            .setMacAddressLogSetting(LogConstants.MAC_ADDRESS_FULL)
            .setUuidsLogSetting(LogConstants.UUIDS_FULL)
            .setShouldLogAttributeValues(true)
            .build()
    );
    RxJavaPlugins.setErrorHandler(throwable -> {
        if (throwable instanceof UndeliverableException && throwable.getCause() instanceof BleException) {
            Log.v("SampleApplication", "Suppressed UndeliverableException: " + throwable.toString());
            return; // ignore BleExceptions as they were surely delivered at least once
        }
        // add other custom handlers if needed
        throw new RuntimeException("Unexpected Throwable in RxJavaPlugins error handler", throwable);
    });
}
 
Example #2
Source File: WriteStreamObserverImpl.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
private void writeStreamEnd(AsyncResult<Void> result) {
  try {
    Action a;
    if (result.succeeded()) {
      synchronized (this) {
        a = writeStreamEndHandler;
      }
      if (a != null) {
        a.run();
      }
    } else {
      Consumer<? super Throwable> c;
      synchronized (this) {
        c = this.writeStreamEndErrorHandler;
      }
      if (c != null) {
        c.accept(result.cause());
      }
    }
  } catch (Throwable t) {
    Exceptions.throwIfFatal(t);
    RxJavaPlugins.onError(t);
  }
}
 
Example #3
Source File: AbstractObjectBoxTest.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpRxSchedulers() {
    Scheduler immediate = new Scheduler() {
        @Override
        public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) {
            // this prevents StackOverflowErrors when scheduling with a delay
            return super.scheduleDirect(run, 0, unit);
        }

        @Override
        public Scheduler.Worker createWorker() {
            return new ExecutorScheduler.ExecutorWorker(Runnable::run, false);
        }
    };

    RxJavaPlugins.setInitIoSchedulerHandler(scheduler -> immediate);
    RxJavaPlugins.setInitComputationSchedulerHandler(scheduler -> immediate);
    RxJavaPlugins.setInitNewThreadSchedulerHandler(scheduler -> immediate);
    RxJavaPlugins.setInitSingleSchedulerHandler(scheduler -> immediate);
    RxAndroidPlugins.setInitMainThreadSchedulerHandler(scheduler -> immediate);
}
 
Example #4
Source File: RxSchedulersRule.java    From quill with MIT License 6 votes vote down vote up
public Statement apply(Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            Scheduler scheduler = TrampolineScheduler.instance();
            Function<Callable<Scheduler>, Scheduler> schedulerFn = __ -> scheduler;
            RxJavaPlugins.reset();
            RxJavaPlugins.setInitIoSchedulerHandler(schedulerFn);
            RxJavaPlugins.setInitNewThreadSchedulerHandler(schedulerFn);
            RxAndroidPlugins.reset();
            RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerFn);

            try {
                base.evaluate();
            } finally {
                RxJavaPlugins.reset();
                RxAndroidPlugins.reset();
            }
        }
    };
}
 
Example #5
Source File: ImmediateSchedulersRule.java    From RxCommand with MIT License 6 votes vote down vote up
@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {

            RxAndroidPlugins.setMainThreadSchedulerHandler(scheduler ->  Schedulers.trampoline());
            RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerCallable ->  Schedulers.trampoline());

            try {
                base.evaluate();
            } finally {
                RxJavaPlugins.reset();
                RxAndroidPlugins.reset();
            }
        }
    };
}
 
Example #6
Source File: RequestContextAssemblyTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void composeWithOtherHook() throws Exception {
    final AtomicInteger calledFlag = new AtomicInteger();
    RxJavaPlugins.setOnSingleAssembly(single -> {
        calledFlag.incrementAndGet();
        return single;
    });
    final WebClient client = WebClient.of(rule.httpUri());
    client.execute(RequestHeaders.of(HttpMethod.GET, "/single")).aggregate().get();
    assertThat(calledFlag.get()).isEqualTo(3);

    try {
        RequestContextAssembly.enable();
        client.execute(RequestHeaders.of(HttpMethod.GET, "/single")).aggregate().get();
        assertThat(calledFlag.get()).isEqualTo(6);
    } finally {
        RequestContextAssembly.disable();
    }
    client.execute(RequestHeaders.of(HttpMethod.GET, "/single")).aggregate().get();
    assertThat(calledFlag.get()).isEqualTo(9);

    RxJavaPlugins.setOnSingleAssembly(null);
    client.execute(RequestHeaders.of(HttpMethod.GET, "/single")).aggregate().get();
    assertThat(calledFlag.get()).isEqualTo(9);
}
 
Example #7
Source File: RxJavaHooksManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenNewThreadScheduler_whenCalled_shouldExecuteTheHook() {

    RxJavaPlugins.setInitNewThreadSchedulerHandler((scheduler) -> {
        initHookCalled = true;
        return scheduler.call();
    });

    RxJavaPlugins.setNewThreadSchedulerHandler((scheduler) -> {
        hookCalled = true;
        return scheduler;
    });

    Observable.range(1, 15)
        .map(v -> v * 2)
        .subscribeOn(Schedulers.newThread())
        .test();
    assertTrue(hookCalled && initHookCalled);
}
 
Example #8
Source File: RxJavaHooksUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenAnyScheduler_whenCalled_shouldExecuteTheHook() {

    RxJavaPlugins.setScheduleHandler((runnable) -> {
        hookCalled = true;
        return runnable;
    });

    Observable.range(1, 10)
        .map(v -> v * 2)
        .subscribeOn(Schedulers.single())
        .test();
    hookCalled = false;
    Observable.range(1, 10)
        .map(v -> v * 2)
        .subscribeOn(Schedulers.computation())
        .test();
    assertTrue(hookCalled);
}
 
Example #9
Source File: RequestContextAssembly.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Disable {@link RequestContext} during operators.
 */
public static synchronized void disable() {
    if (!enabled) {
        return;
    }
    RxJavaPlugins.setOnObservableAssembly(oldOnObservableAssembly);
    oldOnObservableAssembly = null;
    RxJavaPlugins.setOnConnectableObservableAssembly(oldOnConnectableObservableAssembly);
    oldOnConnectableObservableAssembly = null;
    RxJavaPlugins.setOnCompletableAssembly(oldOnCompletableAssembly);
    oldOnCompletableAssembly = null;
    RxJavaPlugins.setOnSingleAssembly(oldOnSingleAssembly);
    oldOnSingleAssembly = null;
    RxJavaPlugins.setOnMaybeAssembly(oldOnMaybeAssembly);
    oldOnMaybeAssembly = null;
    RxJavaPlugins.setOnFlowableAssembly(oldOnFlowableAssembly);
    oldOnFlowableAssembly = null;
    RxJavaPlugins.setOnConnectableFlowableAssembly(oldOnConnectableFlowableAssembly);
    oldOnConnectableFlowableAssembly = null;
    RxJavaPlugins.setOnParallelAssembly(oldOnParallelAssembly);
    oldOnParallelAssembly = null;
    enabled = false;
}
 
Example #10
Source File: RxJavaAssemblyTracking.java    From RxJava2Debug with Apache License 2.0 6 votes vote down vote up
/**
 * Disable the assembly tracking.
 */
public static void disable() {
    if (lock.compareAndSet(false, true)) {

        RxJavaPlugins.setOnCompletableAssembly(null);
        RxJavaPlugins.setOnSingleAssembly(null);
        RxJavaPlugins.setOnMaybeAssembly(null);

        RxJavaPlugins.setOnObservableAssembly(null);
        RxJavaPlugins.setOnFlowableAssembly(null);
        RxJavaPlugins.setOnConnectableObservableAssembly(null);
        RxJavaPlugins.setOnConnectableFlowableAssembly(null);

        RxJavaPlugins.setOnParallelAssembly(null);

        lock.set(false);
    }
}
 
Example #11
Source File: ParallelInterrupt.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    RxJavaPlugins.setErrorHandler(e -> { });
    Flowable.range(1, 10)
    .parallel(4)
    .runOn(Schedulers.io())
    .map(v -> {
       if (v == 2) {
          throw new IOException();
       }
       Thread.sleep(2000);
       return v;
    })
    .sequential()
    .test()
    .awaitDone(5, TimeUnit.SECONDS)
    .assertFailure(IOException.class);
}
 
Example #12
Source File: RxJavaHooksManualTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenIOScheduler_whenCalled_shouldExecuteTheHooks() {

    RxJavaPlugins.setInitIoSchedulerHandler((scheduler) -> {
        initHookCalled = true;
        return scheduler.call();
    });

    RxJavaPlugins.setIoSchedulerHandler((scheduler) -> {
        hookCalled = true;
        return scheduler;
    });

    Observable.range(1, 10)
        .map(v -> v * 2)
        .subscribeOn(Schedulers.io())
        .test();
    assertTrue(hookCalled && initHookCalled);
}
 
Example #13
Source File: HelperTest.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
@Test
public void testToObservableAssemblyHook() {
  FakeStream<String> stream = new FakeStream<>();
  try {
    final Observable<String> justMe = Observable.just("me");
    RxJavaPlugins.setOnObservableAssembly(new Function<Observable, Observable>() {
      @Override public Observable apply(Observable f) {
        return justMe;
      }
    });
    Observable<String> observable = ObservableHelper.toObservable(stream);
    assertSame(observable, justMe);
    Observable<String> observableFn = ObservableHelper.toObservable(stream, identity());
    assertSame(observableFn, justMe);
  } finally {
    RxJavaPlugins.reset();
  }
}
 
Example #14
Source File: CoreConnectionManagerTest.java    From RxCentralBle with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  MockitoAnnotations.initMocks(this);

  RxJavaPlugins.setComputationSchedulerHandler(schedulerCallable -> testScheduler);

  when(scanner.scan()).thenReturn(scanDataPublishSubject.hide());
  when(bluetoothDetector.enabled()).thenReturn(bluetoothEnabledRelay.hide());
  when(peripheralFactory.produce(any(), any())).thenReturn(peripheral);
  when(peripheral.connect()).thenReturn(connectableStatePublishSubject.hide());
  when(scanData.getBluetoothDevice()).thenReturn(bluetoothDevice);

  coreConnectionManager =
      new CoreConnectionManager(
          context, bluetoothDetector, scanner, peripheralFactory);
}
 
Example #15
Source File: AssemblyHooksExample.java    From akarnokd-misc with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
RxJavaPlugins.setOnObservableAssembly(o -> {
    if (o instanceof ObservableFromArray) {
        return new ObservableFromArray<>(new Integer[] { 4, 5, 6 });
    }
    return o;
});

Observable.just(1, 2, 3)
.filter(v -> v > 3)
.test()
.assertResult(4, 5, 6);

RxJavaPlugins.setOnObservableAssembly(null);
}
 
Example #16
Source File: ObservableThrowingTest.java    From retrocache with Apache License 2.0 6 votes vote down vote up
@Test
public void resultThrowingInOnCompletedDeliveredToPlugin() {
    server.enqueue(new MockResponse());

    final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
    RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            if (!throwableRef.compareAndSet(null, throwable)) {
                throw Exceptions.propagate(throwable);
            }
        }
    });

    RecordingObserver<Result<String>> observer = subscriberRule.create();
    final RuntimeException e = new RuntimeException();
    service.result().subscribe(new ForwardingObserver<Result<String>>(observer) {
        @Override
        public void onComplete() {
            throw e;
        }
    });

    observer.assertAnyValue();
    assertThat(throwableRef.get()).isSameAs(e);
}
 
Example #17
Source File: CurrentTraceContextAssemblyTrackingTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void enable_restoresSavedHooks() {
  RxJavaPlugins.reset();

  RxJavaAssemblyTracking.enable();
  try {
    CurrentTraceContextAssemblyTracking.create(currentTraceContext).enable();

    CurrentTraceContextAssemblyTracking.disable();

    Assert.assertNull(RxJavaPlugins.getOnCompletableAssembly());
    Assert.assertNull(RxJavaPlugins.getOnSingleAssembly());
    Assert.assertNull(RxJavaPlugins.getOnMaybeAssembly());
    Assert.assertNull(RxJavaPlugins.getOnObservableAssembly());
    Assert.assertNull(RxJavaPlugins.getOnFlowableAssembly());
    Assert.assertNull(RxJavaPlugins.getOnConnectableFlowableAssembly());
    Assert.assertNull(RxJavaPlugins.getOnConnectableObservableAssembly());
    Assert.assertNull(RxJavaPlugins.getOnParallelAssembly());
  } finally {
    RxJavaAssemblyTracking.disable();
  }
}
 
Example #18
Source File: ObservableThrowingTest.java    From retrocache with Apache License 2.0 5 votes vote down vote up
@Test
public void bodyThrowingInOnCompleteDeliveredToPlugin() {
    server.enqueue(new MockResponse());

    final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
    RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            if (!throwableRef.compareAndSet(null, throwable)) {
                throw Exceptions.propagate(throwable);
            }
        }
    });

    RecordingObserver<String> observer = subscriberRule.create();
    final RuntimeException e = new RuntimeException();
    service.body().subscribe(new ForwardingObserver<String>(observer) {
        @Override
        public void onComplete() {
            throw e;
        }
    });

    observer.assertAnyValue();
    assertThat(throwableRef.get()).isSameAs(e);

}
 
Example #19
Source File: FlowableStateMachineTest.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
@Test
public void testPassThroughEmitterErrorAfterCompletion() {
    List<Throwable> list = new CopyOnWriteArrayList<Throwable>();
    try {
        RxJavaPlugins.setErrorHandler(Consumers.addTo(list));
        FlowableTransformer<Integer, Integer> sm = StateMachine2.builder() //
                .initialState("") //
                .transition(PASS_THROUGH_TRANSITION) //
                .completion(new Completion2<String, Integer>() {
                    @Override
                    public void accept(String state, Emitter<Integer> emitter) {
                        emitter.onComplete_();
                        emitter.onError_(new ThrowingException());
                    }
                }) //
                .requestBatchSize(1) //
                .build();

        Flowable.just(1, 2, 3, 4, 5, 6) //
                .compose(sm) //
                .test() //
                .assertValues(1, 2, 3, 4, 5, 6) //
                .assertComplete();
        assertEquals(1, list.size());
    } finally {
        RxJavaPlugins.reset();
    }

}
 
Example #20
Source File: Application.java    From power-adapters with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    RxJavaPlugins.setErrorHandler(e -> Log.e(TAG, "RxJava error", e));
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    LeakCanary.install(this);
}
 
Example #21
Source File: RxJavaHooksUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenConnectableFlowable_whenAssembled_shouldExecuteTheHook() {

    RxJavaPlugins.setOnConnectableFlowableAssembly(connectableFlowable -> {
        hookCalled = true;
        return connectableFlowable;
    });

    ConnectableFlowable.range(1, 10)
        .publish()
        .connect();
    assertTrue(hookCalled);
}
 
Example #22
Source File: RxJavaBaseActivity.java    From My-MVP with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rx_java_base);
    ButterKnife.bind(this);
    mCompositeDisposable = new CompositeDisposable();

    RxJavaPlugins.setErrorHandler(throwable -> Log.e(TAG, "throwable: " + throwable.getMessage()));
}
 
Example #23
Source File: TestHelper.java    From storio with Apache License 2.0 5 votes vote down vote up
@NonNull
public static List<Throwable> trackPluginErrors() {
    final List<Throwable> list = Collections.synchronizedList(new ArrayList<Throwable>());

    RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
        @Override
        public void accept(Throwable t) {
            list.add(t);
        }
    });

    return list;
}
 
Example #24
Source File: ReadTest.java    From RxCentralBle with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  MockitoAnnotations.initMocks(this);

  RxJavaPlugins.setComputationSchedulerHandler(schedulerCallable -> testScheduler);

  when(peripheral.read(any(), any())).thenReturn(readOperationSingle);

  read = new Read(svcUuid, chrUuid, 5000);
  readResultTestObserver = read.result().test();
}
 
Example #25
Source File: FlowableThrowingTest.java    From retrocache with Apache License 2.0 5 votes vote down vote up
@Test
public void bodyThrowingInOnCompleteDeliveredToPlugin() {
    server.enqueue(new MockResponse());

    final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
    RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            if (!throwableRef.compareAndSet(null, throwable)) {
                throw Exceptions.propagate(throwable);
            }
        }
    });

    RecordingSubscriber<String> subscriber = subscriberRule.create();
    final RuntimeException e = new RuntimeException();
    service.body().subscribe(new ForwardingSubscriber<String>(subscriber) {
        @Override
        public void onComplete() {
            throw e;
        }
    });

    subscriber.assertAnyValue();
    assertThat(throwableRef.get()).isSameAs(e);

}
 
Example #26
Source File: ResultObservable.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
@Override
public void onError(Throwable throwable) {
    try {
        observer.onNext(Result.<R>error(throwable));
    } catch (Throwable t) {
        try {
            observer.onError(t);
        } catch (Throwable inner) {
            Exceptions.throwIfFatal(inner);
            RxJavaPlugins.onError(new CompositeException(t, inner));
        }
        return;
    }
    observer.onComplete();
}
 
Example #27
Source File: CurrentTraceContextAssemblyTrackingMatrixTest.java    From brave with Apache License 2.0 5 votes vote down vote up
Flowable<Integer> callableFlowable(TraceContext expectedCallContext) {
  return RxJavaPlugins.onAssembly(new CallableFlowable() {
    @Override public Integer call() {
      assertThat(currentTraceContext.get()).isEqualTo(expectedCallContext);
      return 1;
    }
  });
}
 
Example #28
Source File: AsyncResultTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testMaybe() {
  Promise<String> promise = Promise.promise();
  try {
    Maybe justMe = Maybe.just("me");
    RxJavaPlugins.setOnMaybeAssembly(single -> justMe);
    Maybe<String> maybe = AsyncResultMaybe.toMaybe(promise.future()::onComplete);
    assertSame(maybe, justMe);
  } finally {
    RxJavaPlugins.reset();
  }
}
 
Example #29
Source File: CurrentTraceContextAssemblyTrackingMatrixTest.java    From brave with Apache License 2.0 5 votes vote down vote up
Flowable<Integer> scalarCallableFlowable(TraceContext expectedCallContext) {
  return RxJavaPlugins.onAssembly(new ScalarCallableFlowable() {
    @Override public Integer call() {
      assertThat(currentTraceContext.get()).isEqualTo(expectedCallContext);
      return 1;
    }
  });
}
 
Example #30
Source File: Subscription.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public static void addErrorHandler(final String TAG) {
    RxJavaPlugins.setErrorHandler(e -> {
        if (e instanceof UndeliverableException) {
            if (!e.getCause().toString().contains("OperationSuccess")) {
                UserError.Log.e(TAG, "RxJavaError: " + e.getMessage());
            }
        } else {
            UserError.Log.wtf(TAG, "RxJavaError2:" + e.getClass().getCanonicalName() + " " + e.getMessage() + " " + JoH.backTrace(3));
        }
    });
}