Search in sources :

Example 16 with Subscription

use of rx.Subscription in project GeekNews by codeestX.

the class TechPresenter method getSearchTechData.

private void getSearchTechData() {
    currentPage = 1;
    Subscription rxSubscription = mRetrofitHelper.fetchGankSearchList(queryStr, currentTech, NUM_OF_PAGE, currentPage).compose(RxUtil.<GankHttpResponse<List<GankSearchItemBean>>>rxSchedulerHelper()).compose(RxUtil.<List<GankSearchItemBean>>handleResult()).map(new Func1<List<GankSearchItemBean>, List<GankItemBean>>() {

        @Override
        public List<GankItemBean> call(List<GankSearchItemBean> gankSearchItemBeen) {
            List<GankItemBean> newList = new ArrayList<>();
            for (GankSearchItemBean item : gankSearchItemBeen) {
                GankItemBean bean = new GankItemBean();
                bean.set_id(item.getGanhuo_id());
                bean.setDesc(item.getDesc());
                bean.setPublishedAt(item.getPublishedAt());
                bean.setWho(item.getWho());
                bean.setUrl(item.getUrl());
                newList.add(bean);
            }
            return newList;
        }
    }).subscribe(new CommonSubscriber<List<GankItemBean>>(mView) {

        @Override
        public void onNext(List<GankItemBean> gankItemBeen) {
            mView.showContent(gankItemBeen);
        }
    });
    addSubscrebe(rxSubscription);
}
Also used : GankHttpResponse(com.codeest.geeknews.model.http.response.GankHttpResponse) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Subscription(rx.Subscription) Func1(rx.functions.Func1) GankItemBean(com.codeest.geeknews.model.bean.GankItemBean) GankSearchItemBean(com.codeest.geeknews.model.bean.GankSearchItemBean)

Example 17 with Subscription

use of rx.Subscription in project Meizhi by drakeet.

the class PictureActivity method saveImageToGallery.

private void saveImageToGallery() {
    // @formatter:off
    Subscription s = RxMeizhi.saveImageAndGetPathObservable(this, mImageUrl, mImageTitle).observeOn(AndroidSchedulers.mainThread()).subscribe(uri -> {
        File appDir = new File(Environment.getExternalStorageDirectory(), "Meizhi");
        String msg = String.format(getString(R.string.picture_has_save_to), appDir.getAbsolutePath());
        Toasts.showShort(msg);
    }, error -> Toasts.showLong(error.getMessage() + "\n再试试..."));
    // @formatter:on
    addSubscription(s);
}
Also used : Subscription(rx.Subscription) File(java.io.File)

Example 18 with Subscription

use of rx.Subscription in project Hystrix by Netflix.

the class AbstractCommand method observe.

/**
     * Used for asynchronous execution of command with a callback by subscribing to the {@link Observable}.
     * <p>
     * This eagerly starts execution of the command the same as {@link HystrixCommand#queue()} and {@link HystrixCommand#execute()}.
     * <p>
     * A lazy {@link Observable} can be obtained from {@link #toObservable()}.
     * <p>
     * See https://github.com/Netflix/RxJava/wiki for more information.
     * 
     * @return {@code Observable<R>} that executes and calls back with the result of command execution or a fallback if the command fails for any reason.
     * @throws HystrixRuntimeException
     *             if a fallback does not exist
     *             <p>
     *             <ul>
     *             <li>via {@code Observer#onError} if a failure occurs</li>
     *             <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li>
     *             </ul>
     * @throws HystrixBadRequestException
     *             via {@code Observer#onError} if invalid arguments or state were used representing a user failure, not a system failure
     * @throws IllegalStateException
     *             if invoked more than once
     */
public Observable<R> observe() {
    // us a ReplaySubject to buffer the eagerly subscribed-to Observable
    ReplaySubject<R> subject = ReplaySubject.create();
    // eagerly kick off subscription
    final Subscription sourceSubscription = toObservable().subscribe(subject);
    // return the subject that can be subscribed to later while the execution has already started
    return subject.doOnUnsubscribe(new Action0() {

        @Override
        public void call() {
            sourceSubscription.unsubscribe();
        }
    });
}
Also used : Action0(rx.functions.Action0) CompositeSubscription(rx.subscriptions.CompositeSubscription) Subscription(rx.Subscription)

Example 19 with Subscription

use of rx.Subscription 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 20 with Subscription

use of rx.Subscription in project Hystrix by Netflix.

the class BucketedCounterStream method unsubscribe.

public void unsubscribe() {
    Subscription s = subscription.get();
    if (s != null) {
        s.unsubscribe();
        subscription.compareAndSet(s, null);
    }
}
Also used : Subscription(rx.Subscription)

Aggregations

Subscription (rx.Subscription)275 Test (org.junit.Test)82 List (java.util.List)66 Action0 (rx.functions.Action0)45 ArrayList (java.util.ArrayList)40 CompositeSubscription (rx.subscriptions.CompositeSubscription)40 CountDownLatch (java.util.concurrent.CountDownLatch)38 Func1 (rx.functions.Func1)24 AtomicReference (java.util.concurrent.atomic.AtomicReference)20 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)19 Observable (rx.Observable)18 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)17 LinkedList (java.util.LinkedList)13 CommandStreamTest (com.netflix.hystrix.metric.CommandStreamTest)11 PlayList (io.github.ryanhoo.music.data.model.PlayList)11 View (android.view.View)10 MetaChangedEvent (io.hefuyi.listener.event.MetaChangedEvent)10 Bundle (android.os.Bundle)9 IOException (java.io.IOException)9 AndroidSchedulers (rx.android.schedulers.AndroidSchedulers)9