Search in sources :

Example 6 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnGracefulFailure.

private RequestContextTestResults testRequestContextOnGracefulFailure(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
    final RequestContextTestResults results = new RequestContextTestResults();
    final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
    TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(circuitBreaker).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {

        @Override
        protected Observable<Boolean> construct() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    s.onError(new RuntimeException("graceful onError"));
                }
            }).subscribeOn(userScheduler);
        }
    };
    results.command = command;
    command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {

        @Override
        public void call(Notification<? super Boolean> n) {
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Run => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(1, results.ts.getOnErrorEvents().size());
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isFailedExecution());
    assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_MISSING);
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) Action1(rx.functions.Action1) TestSubscriber(rx.observers.TestSubscriber) Subscriber(rx.Subscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Notification(rx.Notification)

Example 7 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnTimeoutWithFallback.

private RequestContextTestResults testRequestContextOnTimeoutWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
    final RequestContextTestResults results = new RequestContextTestResults();
    TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker()).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation).withExecutionTimeoutInMilliseconds(50))) {

        @Override
        protected Observable<Boolean> construct() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    // ignore the interrupted exception
                    }
                }
            }).subscribeOn(userScheduler);
        }

        @Override
        protected Observable<Boolean> resumeWithFallback() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    s.onNext(false);
                    s.onCompleted();
                }
            }).subscribeOn(userScheduler);
        }
    };
    results.command = command;
    command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {

        @Override
        public void call(Notification<? super Boolean> n) {
            System.out.println("timeoutWithFallback notification: " + n + "   " + Thread.currentThread());
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Fallback => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(1, results.ts.getOnNextEvents().size());
    assertEquals(false, results.ts.getOnNextEvents().get(0));
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isResponseTimedOut());
    assertCommandExecutionEvents(command, HystrixEventType.TIMEOUT, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) Action1(rx.functions.Action1) TestSubscriber(rx.observers.TestSubscriber) Subscriber(rx.Subscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Notification(rx.Notification)

Example 8 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnFailureWithFallback.

private RequestContextTestResults testRequestContextOnFailureWithFallback(ExecutionIsolationStrategy isolation, final Scheduler userScheduler) {
    final RequestContextTestResults results = new RequestContextTestResults();
    TestHystrixObservableCommand<Boolean> command = new TestHystrixObservableCommand<Boolean>(TestHystrixObservableCommand.testPropsBuilder(new TestCircuitBreaker()).setCommandPropertiesDefaults(HystrixCommandPropertiesTest.getUnitTestPropertiesSetter().withExecutionIsolationStrategy(isolation))) {

        @Override
        protected Observable<Boolean> construct() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    s.onError(new RuntimeException("onError"));
                }
            }).subscribeOn(userScheduler);
        }

        @Override
        protected Observable<Boolean> resumeWithFallback() {
            return Observable.create(new OnSubscribe<Boolean>() {

                @Override
                public void call(Subscriber<? super Boolean> s) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    s.onNext(false);
                    s.onCompleted();
                }
            }).subscribeOn(userScheduler);
        }
    };
    results.command = command;
    command.toObservable().doOnEach(new Action1<Notification<? super Boolean>>() {

        @Override
        public void call(Notification<? super Boolean> n) {
            results.isContextInitializedObserveOn.set(HystrixRequestContext.isCurrentThreadInitialized());
            results.observeOnThread.set(Thread.currentThread());
        }
    }).subscribe(results.ts);
    results.ts.awaitTerminalEvent();
    System.out.println("Run => Initialized: " + results.isContextInitialized.get() + "  Thread: " + results.originThread.get());
    System.out.println("Observed => Initialized: " + results.isContextInitializedObserveOn.get() + "  Thread: " + results.observeOnThread.get());
    assertEquals(0, results.ts.getOnErrorEvents().size());
    assertEquals(1, results.ts.getOnNextEvents().size());
    assertEquals(false, results.ts.getOnNextEvents().get(0));
    assertTrue(command.getExecutionTimeInMilliseconds() > -1);
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isFailedExecution());
    assertCommandExecutionEvents(command, HystrixEventType.FAILURE, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    assertEquals(0, command.metrics.getCurrentConcurrentExecutionCount());
    assertSaneHystrixRequestLog(1);
    return results;
}
Also used : TestCircuitBreaker(com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) Action1(rx.functions.Action1) TestSubscriber(rx.observers.TestSubscriber) Subscriber(rx.Subscriber) OnSubscribe(rx.Observable.OnSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Notification(rx.Notification)

Example 9 with Subscriber

use of rx.Subscriber in project archi by ivacf.

the class MainViewModel method loadGithubRepos.

private void loadGithubRepos(String username) {
    progressVisibility.set(View.VISIBLE);
    recyclerViewVisibility.set(View.INVISIBLE);
    infoMessageVisibility.set(View.INVISIBLE);
    if (subscription != null && !subscription.isUnsubscribed())
        subscription.unsubscribe();
    ArchiApplication application = ArchiApplication.get(context);
    GithubService githubService = application.getGithubService();
    subscription = githubService.publicRepositories(username).observeOn(AndroidSchedulers.mainThread()).subscribeOn(application.defaultSubscribeScheduler()).subscribe(new Subscriber<List<Repository>>() {

        @Override
        public void onCompleted() {
            if (dataListener != null)
                dataListener.onRepositoriesChanged(repositories);
            progressVisibility.set(View.INVISIBLE);
            if (!repositories.isEmpty()) {
                recyclerViewVisibility.set(View.VISIBLE);
            } else {
                infoMessage.set(context.getString(R.string.text_empty_repos));
                infoMessageVisibility.set(View.VISIBLE);
            }
        }

        @Override
        public void onError(Throwable error) {
            Log.e(TAG, "Error loading GitHub repos ", error);
            progressVisibility.set(View.INVISIBLE);
            if (isHttp404(error)) {
                infoMessage.set(context.getString(R.string.error_username_not_found));
            } else {
                infoMessage.set(context.getString(R.string.error_loading_repos));
            }
            infoMessageVisibility.set(View.VISIBLE);
        }

        @Override
        public void onNext(List<Repository> repositories) {
            Log.i(TAG, "Repos loaded " + repositories);
            MainViewModel.this.repositories = repositories;
        }
    });
}
Also used : GithubService(uk.ivanc.archimvvm.model.GithubService) Repository(uk.ivanc.archimvvm.model.Repository) ArchiApplication(uk.ivanc.archimvvm.ArchiApplication) Subscriber(rx.Subscriber) List(java.util.List)

Example 10 with Subscriber

use of rx.Subscriber in project sqlbrite by square.

the class BriteContentResolver method createQuery.

/**
   * Create an observable which will notify subscribers with a {@linkplain Query query} for
   * execution. Subscribers are responsible for <b>always</b> closing {@link Cursor} instance
   * returned from the {@link Query}.
   * <p>
   * Subscribers will receive an immediate notification for initial data as well as subsequent
   * notifications for when the supplied {@code uri}'s data changes. Unsubscribe when you no longer
   * want updates to a query.
   * <p>
   * Since content resolver triggers are inherently asynchronous, items emitted from the returned
   * observable use the {@link Scheduler} supplied to {@link SqlBrite#wrapContentProvider}. For
   * consistency, the immediate notification sent on subscribe also uses this scheduler. As such,
   * calling {@link Observable#subscribeOn subscribeOn} on the returned observable has no effect.
   * <p>
   * Note: To skip the immediate notification and only receive subsequent notifications when data
   * has changed call {@code skip(1)} on the returned observable.
   * <p>
   * <b>Warning:</b> this method does not perform the query! Only by subscribing to the returned
   * {@link Observable} will the operation occur.
   *
   * @see ContentResolver#query(Uri, String[], String, String[], String)
   * @see ContentResolver#registerContentObserver(Uri, boolean, ContentObserver)
   */
@CheckResult
@NonNull
public QueryObservable createQuery(@NonNull final Uri uri, @Nullable final String[] projection, @Nullable final String selection, @Nullable final String[] selectionArgs, @Nullable final String sortOrder, final boolean notifyForDescendents) {
    final Query query = new Query() {

        @Override
        public Cursor run() {
            long startNanos = nanoTime();
            Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
            if (logging) {
                long tookMillis = NANOSECONDS.toMillis(nanoTime() - startNanos);
                log("QUERY (%sms)\n  uri: %s\n  projection: %s\n  selection: %s\n  selectionArgs: %s\n  " + "sortOrder: %s\n  notifyForDescendents: %s", tookMillis, uri, Arrays.toString(projection), selection, Arrays.toString(selectionArgs), sortOrder, notifyForDescendents);
            }
            return cursor;
        }
    };
    OnSubscribe<Query> subscribe = new OnSubscribe<Query>() {

        @Override
        public void call(final Subscriber<? super Query> subscriber) {
            final ContentObserver observer = new ContentObserver(contentObserverHandler) {

                @Override
                public void onChange(boolean selfChange) {
                    subscriber.onNext(query);
                }
            };
            contentResolver.registerContentObserver(uri, notifyForDescendents, observer);
            subscriber.add(Subscriptions.create(new Action0() {

                @Override
                public void call() {
                    contentResolver.unregisterContentObserver(observer);
                }
            }));
            // Trigger initial query.
            subscriber.onNext(query);
        }
    };
    final Observable<Query> queryObservable = //
    Observable.create(subscribe).onBackpressureLatest().observeOn(//
    scheduler).compose(// Apply the user's query transformer.
    queryTransformer).onBackpressureLatest();
    // TODO switch to .to() when non-@Experimental
    return new QueryObservable(new OnSubscribe<Query>() {

        @Override
        public void call(Subscriber<? super Query> subscriber) {
            queryObservable.unsafeSubscribe(subscriber);
        }
    });
}
Also used : Action0(rx.functions.Action0) Query(com.squareup.sqlbrite.SqlBrite.Query) Subscriber(rx.Subscriber) OnSubscribe(rx.Observable.OnSubscribe) Cursor(android.database.Cursor) ContentObserver(android.database.ContentObserver) CheckResult(android.support.annotation.CheckResult) NonNull(android.support.annotation.NonNull)

Aggregations

Subscriber (rx.Subscriber)48 List (java.util.List)16 Observable (rx.Observable)15 IOException (java.io.IOException)11 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)10 Action1 (rx.functions.Action1)10 Schedulers (rx.schedulers.Schedulers)10 Context (android.content.Context)8 ArrayList (java.util.ArrayList)8 OnSubscribe (rx.Observable.OnSubscribe)8 TestCircuitBreaker (com.netflix.hystrix.HystrixCircuitBreakerTest.TestCircuitBreaker)7 RxException (com.yydcdut.note.model.rx.exception.RxException)7 Notification (rx.Notification)7 TestSubscriber (rx.observers.TestSubscriber)7 Cursor (android.database.Cursor)5 ContextLife (com.yydcdut.note.injector.ContextLife)5 Map (java.util.Map)5 Inject (javax.inject.Inject)5 Subscription (rx.Subscription)5 Action0 (rx.functions.Action0)5