Search in sources :

Example 1 with Subscriber

use of rx.Subscriber in project UltimateAndroid by cymcsg.

the class RepositoryPresenter method loadRepositoryInfo.

public void loadRepositoryInfo() {
    repositoryView.showProgressBar();
    Subscriber subscriber = new Subscriber<RepositoryList<List<Repository>>>() {

        @Override
        public void onCompleted() {
            Logs.d("completed");
        }

        @Override
        public void onError(Throwable e) {
            Logs.e(e.getMessage());
        }

        @Override
        public void onNext(RepositoryList<List<Repository>> repositoryList) {
            repositoryView.setReposotories(repositoryList);
        }
    };
    //  GithubApiService.getInstance().loadRepositoryInfo(subscriber, "ultimate", "java");
    GithubApiService.getInstance().loadRepositoryInfo(subscriber, "stars:>100", "java");
}
Also used : Repository(com.marshalchen.ultimateandroid.demo.model.Repository) Subscriber(rx.Subscriber) RepositoryList(com.marshalchen.ultimateandroid.demo.model.RepositoryList) RepositoryList(com.marshalchen.ultimateandroid.demo.model.RepositoryList) List(java.util.List)

Example 2 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixSampleSseServlet method handleRequest.

/**
     * - maintain an open connection with the client
     * - on initial connection send latest data of each requested event type
     * - subsequently send all changes for each requested event type
     *
     * @param request  incoming HTTP Request
     * @param response outgoing HTTP Response (as a streaming response)
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
private void handleRequest(HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    final AtomicBoolean moreDataWillBeSent = new AtomicBoolean(true);
    Subscription sampleSubscription = null;
    /* ensure we aren't allowing more connections than we want */
    int numberConnections = incrementAndGetCurrentConcurrentConnections();
    try {
        //may change at runtime, so look this up for each request
        int maxNumberConnectionsAllowed = getMaxNumberConcurrentConnectionsAllowed();
        if (numberConnections > maxNumberConnectionsAllowed) {
            response.sendError(503, "MaxConcurrentConnections reached: " + maxNumberConnectionsAllowed);
        } else {
            /* initialize response */
            response.setHeader("Content-Type", "text/event-stream;charset=UTF-8");
            response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            final PrintWriter writer = response.getWriter();
            //since the sample stream is based on Observable.interval, events will get published on an RxComputation thread
            //since writing to the servlet response is blocking, use the Rx IO thread for the write that occurs in the onNext
            sampleSubscription = sampleStream.observeOn(Schedulers.io()).subscribe(new Subscriber<String>() {

                @Override
                public void onCompleted() {
                    logger.error("HystrixSampleSseServlet: ({}) received unexpected OnCompleted from sample stream", getClass().getSimpleName());
                    moreDataWillBeSent.set(false);
                }

                @Override
                public void onError(Throwable e) {
                    moreDataWillBeSent.set(false);
                }

                @Override
                public void onNext(String sampleDataAsString) {
                    if (sampleDataAsString != null) {
                        writer.print("data: " + sampleDataAsString + "\n\n");
                        // explicitly check for client disconnect - PrintWriter does not throw exceptions
                        if (writer.checkError()) {
                            moreDataWillBeSent.set(false);
                        }
                        writer.flush();
                    }
                }
            });
            while (moreDataWillBeSent.get() && !isDestroyed) {
                try {
                    Thread.sleep(pausePollerThreadDelayInMs);
                    //in case stream has not started emitting yet, catch any clients which connect/disconnect before emits start
                    writer.print("ping: \n\n");
                    // explicitly check for client disconnect - PrintWriter does not throw exceptions
                    if (writer.checkError()) {
                        moreDataWillBeSent.set(false);
                    }
                    writer.flush();
                } catch (InterruptedException e) {
                    moreDataWillBeSent.set(false);
                }
            }
        }
    } finally {
        decrementCurrentConcurrentConnections();
        if (sampleSubscription != null && !sampleSubscription.isUnsubscribed()) {
            sampleSubscription.unsubscribe();
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Subscriber(rx.Subscriber) Subscription(rx.Subscription) PrintWriter(java.io.PrintWriter)

Example 3 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixStreamingOutputProvider method writeTo.

@Override
public void writeTo(HystrixStream o, Class<?> t, Type gt, Annotation[] as, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, final OutputStream entity) throws IOException {
    Subscription sampleSubscription = null;
    final AtomicBoolean moreDataWillBeSent = new AtomicBoolean(true);
    try {
        sampleSubscription = o.getSampleStream().observeOn(Schedulers.io()).subscribe(new Subscriber<String>() {

            @Override
            public void onCompleted() {
                LOGGER.error("HystrixSampleSseServlet: ({}) received unexpected OnCompleted from sample stream", getClass().getSimpleName());
                moreDataWillBeSent.set(false);
            }

            @Override
            public void onError(Throwable e) {
                moreDataWillBeSent.set(false);
            }

            @Override
            public void onNext(String sampleDataAsString) {
                if (sampleDataAsString != null) {
                    try {
                        entity.write(("data: " + sampleDataAsString + "\n\n").getBytes());
                        entity.flush();
                    } catch (IOException ioe) {
                        moreDataWillBeSent.set(false);
                    }
                }
            }
        });
        while (moreDataWillBeSent.get()) {
            try {
                Thread.sleep(o.getPausePollerThreadDelayInMs());
            } catch (InterruptedException e) {
                moreDataWillBeSent.set(false);
            }
        }
    } finally {
        o.getConcurrentConnections().decrementAndGet();
        if (sampleSubscription != null && !sampleSubscription.isUnsubscribed()) {
            sampleSubscription.unsubscribe();
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Subscriber(rx.Subscriber) IOException(java.io.IOException) Subscription(rx.Subscription)

Example 4 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnRejectionWithFallback.

private RequestContextTestResults testRequestContextOnRejectionWithFallback(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).withExecutionIsolationSemaphoreMaxConcurrentRequests(0)).setThreadPool(new HystrixThreadPool() {

        @Override
        public ThreadPoolExecutor getExecutor() {
            return null;
        }

        @Override
        public void markThreadExecution() {
        }

        @Override
        public void markThreadCompletion() {
        }

        @Override
        public void markThreadRejection() {
        }

        @Override
        public boolean isQueueSpaceAvailable() {
            // always return false so we reject everything
            return false;
        }

        @Override
        public Scheduler getScheduler() {
            return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this);
        }

        @Override
        public Scheduler getScheduler(Func0<Boolean> shouldInterruptThread) {
            return new HystrixContextScheduler(HystrixPlugins.getInstance().getConcurrencyStrategy(), this, shouldInterruptThread);
        }
    })) {

        @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));
    assertFalse(command.isSuccessfulExecution());
    assertTrue(command.isResponseRejected());
    if (isolation == ExecutionIsolationStrategy.SEMAPHORE) {
        assertCommandExecutionEvents(command, HystrixEventType.SEMAPHORE_REJECTED, HystrixEventType.FALLBACK_EMIT, HystrixEventType.FALLBACK_SUCCESS);
    } else {
        assertCommandExecutionEvents(command, HystrixEventType.THREAD_POOL_REJECTED, 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) HystrixContextScheduler(com.netflix.hystrix.strategy.concurrency.HystrixContextScheduler) OnSubscribe(rx.Observable.OnSubscribe) Notification(rx.Notification) HystrixRuntimeException(com.netflix.hystrix.exception.HystrixRuntimeException) TestSubscriber(rx.observers.TestSubscriber) Subscriber(rx.Subscriber) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Func0(rx.functions.Func0)

Example 5 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnShortCircuitedWithFallback.

private RequestContextTestResults testRequestContextOnShortCircuitedWithFallback(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)).setCircuitBreaker(new TestCircuitBreaker().setForceShortCircuit(true))) {

        @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.isResponseShortCircuited());
    assertCommandExecutionEvents(command, HystrixEventType.SHORT_CIRCUITED, 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)

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