Search in sources :

Example 36 with Subscriber

use of rx.Subscriber in project Hystrix by Netflix.

the class HystrixObservableCommandTest method testRequestContextOnBadFailure.

private RequestContextTestResults testRequestContextOnBadFailure(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) {
                    results.isContextInitialized.set(HystrixRequestContext.isCurrentThreadInitialized());
                    results.originThread.set(Thread.currentThread());
                    throw new RuntimeException("bad 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 37 with Subscriber

use of rx.Subscriber in project Rutgers-Course-Tracker by tevjef.

the class SectionInfoPresenterImpl method loadRMP.

public void loadRMP() {
    final Iterable<Instructors> professorsNotFound = new ArrayList<>(mSection.getInstructors());
    cancePreviousSubscription();
    Subscriber<Professor> subscriber = new Subscriber<Professor>() {

        @Override
        public void onCompleted() {
        }

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

        @Override
        public void onNext(Professor professor) {
            if (getView() != null)
                getView().addRMPProfessor(professor);
        }
    };
    mSubscription = buildSearchParameters(mSection).flatMap(new Func1<Parameter, Observable<Professor>>() {

        @Override
        public Observable<Professor> call(Parameter parameter) {
            return rmp.getProfessor(parameter);
        }
    }).doOnNext(new Action1<Professor>() {

        @Override
        public void call(Professor professor) {
            for (final Iterator<Instructors> iterator = professorsNotFound.iterator(); iterator.hasNext(); ) {
                Instructors i = iterator.next();
                if (StringUtils.getJaroWinklerDistance(i.getLastName(), professor.getLastName()) > .70 || StringUtils.getJaroWinklerDistance(i.getLastName(), professor.getFirstName()) > .70) {
                    iterator.remove();
                }
            }
        }
    }).subscribeOn(mBackgroundThread).observeOn(mMainThread).doOnTerminate(new Action0() {

        @Override
        public void call() {
            if (getView() != null) {
                getView().showRatingsLayout();
                getView().hideRatingsLoading();
                for (Instructors i : professorsNotFound) {
                    getView().addErrorProfessor(i.getName());
                }
            }
        }
    }).subscribe(subscriber);
}
Also used : Professor(com.tevinjeffrey.rmp.common.Professor) Action0(rx.functions.Action0) Action1(rx.functions.Action1) ArrayList(java.util.ArrayList) Observable(rx.Observable) Instructors(com.tevinjeffrey.rutgersct.rutgersapi.model.Course.Section.Instructors) Subscriber(rx.Subscriber) Parameter(com.tevinjeffrey.rmp.common.Parameter)

Example 38 with Subscriber

use of rx.Subscriber in project mortar by square.

the class Chat method getMessages.

public Observable<Message> getMessages() {
    return Observable.create(new Observable.OnSubscribe<Message>() {

        @Override
        public void call(final Subscriber<? super Message> subscriber) {
            final Random random = new Random();
            while (true) {
                if (random.nextInt(PROBABILITY) == 0) {
                    try {
                        User from = users.get(random.nextInt(users.size()));
                        Message next = new Message(from, chats.service.getQuote().quote);
                        messages.add(next);
                        if (!subscriber.isUnsubscribed()) {
                            subscriber.onNext(next);
                        }
                    } catch (RetrofitError e) {
                        if (!subscriber.isUnsubscribed()) {
                            subscriber.onError(e);
                            break;
                        }
                    }
                }
                try {
                    // Hijacking the thread like this is sleazey, but you get the idea.
                    Thread.sleep(SLEEP_MILLIS);
                } catch (InterruptedException e) {
                    if (!subscriber.isUnsubscribed()) {
                        subscriber.onError(e);
                    }
                    break;
                }
            }
        }
    }).startWith(//
    messages).subscribeOn(//
    Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
Also used : Random(java.util.Random) Subscriber(rx.Subscriber) RetrofitError(retrofit.RetrofitError)

Example 39 with Subscriber

use of rx.Subscriber in project bilibili-android-client by HotBitmapGG.

the class BiliDanmukuDownloadUtil method downloadXML.

public static Observable<BaseDanmakuParser> downloadXML(final String uri) {
    return Observable.create(new Observable.OnSubscribe<BaseDanmakuParser>() {

        @Override
        public void call(final Subscriber<? super BaseDanmakuParser> subscriber) {
            if (TextUtils.isEmpty(uri)) {
                subscriber.onNext(new BaseDanmakuParser() {

                    @Override
                    protected IDanmakus parse() {
                        return new Danmakus();
                    }
                });
            }
            ILoader loader = null;
            try {
                HttpConnection.Response rsp = (HttpConnection.Response) Jsoup.connect(uri).timeout(20000).execute();
                InputStream stream = new ByteArrayInputStream(BiliDanmukuCompressionTools.decompressXML(rsp.bodyAsBytes()));
                loader = DanmakuLoaderFactory.create(DanmakuLoaderFactory.TAG_BILI);
                loader.load(stream);
            } catch (IOException | DataFormatException | IllegalDataException e) {
                e.printStackTrace();
            }
            BaseDanmakuParser parser = new BiliDanmukuParser();
            assert loader != null;
            IDataSource<?> dataSource = loader.getDataSource();
            parser.load(dataSource);
            subscriber.onNext(parser);
        }
    }).subscribeOn(Schedulers.io());
}
Also used : BaseDanmakuParser(master.flame.danmaku.danmaku.parser.BaseDanmakuParser) HttpConnection(org.jsoup.helper.HttpConnection) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IDanmakus(master.flame.danmaku.danmaku.model.IDanmakus) Danmakus(master.flame.danmaku.danmaku.model.android.Danmakus) IOException(java.io.IOException) DataFormatException(java.util.zip.DataFormatException) Subscriber(rx.Subscriber) ByteArrayInputStream(java.io.ByteArrayInputStream) ILoader(master.flame.danmaku.danmaku.loader.ILoader) IDanmakus(master.flame.danmaku.danmaku.model.IDanmakus) IllegalDataException(master.flame.danmaku.danmaku.loader.IllegalDataException)

Example 40 with Subscriber

use of rx.Subscriber in project WSPerfLab by Netflix-Skunkworks.

the class MockResponse method generateJson.

/**
     * 
     * @param id
     *            ID from client used to assert correct client/server interaction
     * @param delay
     *            How long to delay delivery to simulate server-side latency
     * @param itemSize
     *            Length of each item String.
     * @param numItems
     *            Number of items in response.
     * 
     * @return String json
     */
public static Observable<ByteBuf> generateJson(long id, int delay, int itemSize, int numItems) {
    return Observable.create((Subscriber<? super ByteBuf> subscriber) -> {
        Worker worker = Schedulers.computation().createWorker();
        subscriber.add(worker);
        worker.schedule(() -> {
            try {
                ByteBuf buffer = Unpooled.buffer();
                ByteBufOutputStream jsonAsBytes = new ByteBufOutputStream(buffer);
                JsonGenerator json = jsonFactory.createJsonGenerator(jsonAsBytes);
                json.writeStartObject();
                // manipulate the ID such that we can know the response is from the server (client will know the logic)
                long responseKey = getResponseKey(id);
                json.writeNumberField("responseKey", responseKey);
                json.writeNumberField("delay", delay);
                if (itemSize > MAX_ITEM_LENGTH) {
                    throw new IllegalArgumentException("itemSize can not be larger than: " + MAX_ITEM_LENGTH);
                }
                json.writeNumberField("itemSize", itemSize);
                json.writeNumberField("numItems", numItems);
                json.writeArrayFieldStart("items");
                for (int i = 0; i < numItems; i++) {
                    json.writeString(RAW_ITEM_LONG.substring(0, itemSize));
                }
                json.writeEndArray();
                json.writeEndObject();
                json.close();
                subscriber.onNext(buffer);
                subscriber.onCompleted();
            } catch (Exception e) {
                subscriber.onError(e);
            }
        }, delay, TimeUnit.MILLISECONDS);
    });
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) Subscriber(rx.Subscriber) Worker(rx.Scheduler.Worker) JsonGenerator(org.codehaus.jackson.JsonGenerator) ByteBuf(io.netty.buffer.ByteBuf) JsonGenerationException(org.codehaus.jackson.JsonGenerationException) IOException(java.io.IOException)

Aggregations

Subscriber (rx.Subscriber)50 List (java.util.List)16 Observable (rx.Observable)16 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 File (java.io.File)6 Cursor (android.database.Cursor)5 View (android.view.View)5 ContextLife (com.yydcdut.note.injector.ContextLife)5 Map (java.util.Map)5 Inject (javax.inject.Inject)5