Search in sources :

Example 16 with NonNull

use of io.reactivex.annotations.NonNull in project RxJavaInAction by fengzhizi715.

the class TestHttpClientWithObservable method main.

public static void main(String[] args) {
    Observable.create(new ObservableOnSubscribe<String>() {

        @Override
        public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
            String url = "http://www.163.com";
            e.onNext(url);
        }
    }).map(new io.reactivex.functions.Function<String, CloseableHttpResponse>() {

        @Override
        public CloseableHttpResponse apply(@NonNull String url) throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            return client.execute(get);
        }
    }).subscribe(new Consumer<CloseableHttpResponse>() {

        @Override
        public void accept(CloseableHttpResponse response) throws Exception {
            // 服务器返回码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("statusCode = " + statusCode);
            HttpEntity entity = response.getEntity();
            // 服务器返回内容
            String respStr = null;
            if (entity != null) {
                respStr = EntityUtils.toString(entity, "UTF-8");
            }
            System.out.println(respStr);
            // 释放资源
            EntityUtils.consume(entity);
        }
    });
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) NonNull(io.reactivex.annotations.NonNull) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 17 with NonNull

use of io.reactivex.annotations.NonNull in project RxJavaInAction by fengzhizi715.

the class TestHttpClientWithPoolAndMaybe method httpGet.

/**
 * GET请求
 *
 * @param url     请求地址
 * @param timeOut 超时时间
 * @return
 */
public static Maybe<String> httpGet(String url, int timeOut) {
    return Maybe.create(new MaybeOnSubscribe<String>() {

        @Override
        public void subscribe(@NonNull MaybeEmitter<String> e) throws Exception {
            e.onSuccess(url);
        }
    }).map(new Function<String, String>() {

        @Override
        public String apply(@NonNull String s) throws Exception {
            // 获取客户端连接对象
            CloseableHttpClient httpClient = getHttpClient(timeOut);
            // 创建GET请求对象
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String msg = null;
            try {
                // 执行请求
                response = httpClient.execute(httpGet);
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                // 获取响应信息
                msg = EntityUtils.toString(entity, "UTF-8");
            } catch (ClientProtocolException e) {
                System.err.println("协议错误");
                e.printStackTrace();
            } catch (ParseException e) {
                System.err.println("解析错误");
                e.printStackTrace();
            } catch (IOException e) {
                System.err.println("IO错误");
                e.printStackTrace();
            } finally {
                if (response != null) {
                    try {
                        EntityUtils.consume(response.getEntity());
                        response.close();
                    } catch (IOException e) {
                        System.err.println("释放链接错误");
                        e.printStackTrace();
                    }
                }
            }
            return msg;
        }
    });
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) MaybeEmitter(io.reactivex.MaybeEmitter) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.apache.http.ParseException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) NonNull(io.reactivex.annotations.NonNull) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) MaybeOnSubscribe(io.reactivex.MaybeOnSubscribe) ParseException(org.apache.http.ParseException)

Example 18 with NonNull

use of io.reactivex.annotations.NonNull in project RxJavaInAction by fengzhizi715.

the class RoundRobinForParallel2 method main.

public static void main(String[] args) {
    final AtomicInteger batch = new AtomicInteger(0);
    int threadNum = 5;
    final ExecutorService executor = Executors.newFixedThreadPool(threadNum);
    final Scheduler scheduler = Schedulers.from(executor);
    Observable.range(1, 100).groupBy(new Function<Integer, Integer>() {

        @Override
        public Integer apply(@NonNull Integer integer) throws Exception {
            return batch.getAndIncrement() % threadNum;
        }
    }).flatMap(new Function<GroupedObservable<Integer, Integer>, ObservableSource<?>>() {

        @Override
        public ObservableSource<?> apply(@NonNull GroupedObservable<Integer, Integer> integerIntegerGroupedObservable) throws Exception {
            return integerIntegerGroupedObservable.observeOn(scheduler).map(new Function<Integer, String>() {

                @Override
                public String apply(@NonNull Integer integer) throws Exception {
                    return integer.toString();
                }
            });
        }
    }).subscribe(new Consumer<Object>() {

        @Override
        public void accept(@NonNull Object o) throws Exception {
            System.out.println(o);
        }
    });
}
Also used : Scheduler(io.reactivex.Scheduler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Function(io.reactivex.functions.Function) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NonNull(io.reactivex.annotations.NonNull) ExecutorService(java.util.concurrent.ExecutorService) GroupedObservable(io.reactivex.observables.GroupedObservable)

Example 19 with NonNull

use of io.reactivex.annotations.NonNull in project okhttp-OkGo by jeasonlzy.

the class RxFormUploadActivity method formUpload2.

@OnClick(R.id.formUpload2)
public void formUpload2(View view) {
    final ArrayList<File> files = new ArrayList<>();
    if (imageItems != null && imageItems.size() > 0) {
        for (int i = 0; i < imageItems.size(); i++) {
            files.add(new File(imageItems.get(i).path));
        }
    }
    Observable.create(new ObservableOnSubscribe<Progress>() {

        @Override
        public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
            // 
            OkGo.<String>post(Urls.URL_FORM_UPLOAD).tag(// 
            this).headers("header1", // 
            "headerValue1").headers("header2", // 
            "headerValue2").params("param1", // 
            "paramValue1").params("param2", // 
            "paramValue2").addFileParams("file", // 
            files).execute(new StringCallback() {

                @Override
                public void onSuccess(Response<String> response) {
                    e.onComplete();
                }

                @Override
                public void onError(Response<String> response) {
                    e.onError(response.getException());
                }

                @Override
                public void uploadProgress(Progress progress) {
                    e.onNext(progress);
                }
            });
        }
    }).doOnSubscribe(new Consumer<Disposable>() {

        @Override
        public void accept(@NonNull Disposable disposable) throws Exception {
            btnFormUpload2.setText("正在上传中...");
        }
    }).observeOn(// 
    AndroidSchedulers.mainThread()).subscribe(new Observer<Progress>() {

        @Override
        public void onSubscribe(@NonNull Disposable d) {
            addDisposable(d);
        }

        @Override
        public void onNext(@NonNull Progress progress) {
            System.out.println("uploadProgress: " + progress);
            String downloadLength = Formatter.formatFileSize(getApplicationContext(), progress.currentSize);
            String totalLength = Formatter.formatFileSize(getApplicationContext(), progress.totalSize);
            tvDownloadSize.setText(downloadLength + "/" + totalLength);
            String speed = Formatter.formatFileSize(getApplicationContext(), progress.speed);
            tvNetSpeed.setText(String.format("%s/s", speed));
            tvProgress.setText(numberFormat.format(progress.fraction));
            pbProgress.setMax(10000);
            pbProgress.setProgress((int) (progress.fraction * 10000));
        }

        @Override
        public void onError(@NonNull Throwable e) {
            e.printStackTrace();
            btnFormUpload2.setText("上传出错");
            showToast(e.getMessage());
        }

        @Override
        public void onComplete() {
            btnFormUpload2.setText("上传完成");
        }
    });
}
Also used : Disposable(io.reactivex.disposables.Disposable) Progress(com.lzy.okgo.model.Progress) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) ArrayList(java.util.ArrayList) StringCallback(com.lzy.okgo.callback.StringCallback) NonNull(io.reactivex.annotations.NonNull) File(java.io.File) ObservableEmitter(io.reactivex.ObservableEmitter) OnClick(butterknife.OnClick)

Example 20 with NonNull

use of io.reactivex.annotations.NonNull in project SimpleCropView by IsseiAoki.

the class CropImageView method loadAsCompletable.

/**
 * Load image from Uri with RxJava2
 *
 * @param sourceUri Image Uri
 *
 * @see #load(Uri)
 *
 * @return Completable of loading image
 */
public Completable loadAsCompletable(final Uri sourceUri, final boolean useThumbnail, final RectF initialFrameRect) {
    return Completable.create(new CompletableOnSubscribe() {

        @Override
        public void subscribe(@NonNull final CompletableEmitter emitter) throws Exception {
            mInitialFrameRect = initialFrameRect;
            mSourceUri = sourceUri;
            if (useThumbnail) {
                applyThumbnail(sourceUri);
            }
            final Bitmap sampled = getImage(sourceUri);
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    mAngle = mExifRotation;
                    setImageDrawableInternal(new BitmapDrawable(getResources(), sampled));
                    emitter.onComplete();
                }
            });
        }
    }).doOnSubscribe(new Consumer<Disposable>() {

        @Override
        public void accept(@NonNull Disposable disposable) throws Exception {
            mIsLoading.set(true);
        }
    }).doFinally(new Action() {

        @Override
        public void run() throws Exception {
            mIsLoading.set(false);
        }
    });
}
Also used : Disposable(io.reactivex.disposables.Disposable) Bitmap(android.graphics.Bitmap) Action(io.reactivex.functions.Action) Consumer(io.reactivex.functions.Consumer) NonNull(io.reactivex.annotations.NonNull) BitmapDrawable(android.graphics.drawable.BitmapDrawable) CompletableOnSubscribe(io.reactivex.CompletableOnSubscribe) IOException(java.io.IOException) CompletableEmitter(io.reactivex.CompletableEmitter)

Aggregations

NonNull (io.reactivex.annotations.NonNull)39 Disposable (io.reactivex.disposables.Disposable)17 CompositeDisposable (io.reactivex.disposables.CompositeDisposable)15 Consumer (io.reactivex.functions.Consumer)14 Function (io.reactivex.functions.Function)13 BuildDetails (com.khmelenko.lab.varis.network.response.BuildDetails)6 OnClick (butterknife.OnClick)5 List (java.util.List)5 RequestBody (okhttp3.RequestBody)5 ObservableEmitter (io.reactivex.ObservableEmitter)4 ObservableOnSubscribe (io.reactivex.ObservableOnSubscribe)4 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Headers (okhttp3.Headers)3 View (android.view.View)2 ANError (com.androidnetworking.error.ANError)2 User (com.khmelenko.lab.varis.network.response.User)2 LzyResponse (com.lzy.demo.model.LzyResponse)2 ServerModel (com.lzy.demo.model.ServerModel)2 Action (io.reactivex.functions.Action)2