Search in sources :

Example 6 with ObservableEmitter

use of io.reactivex.ObservableEmitter in project RxJavaInAction by fengzhizi715.

the class TestRxAndroid2Activity method initData.

private void initData() {
    Observable.create(new ObservableOnSubscribe<String>() {

        @Override
        public void subscribe(ObservableEmitter<String> e) throws Exception {
            L.i("IMAGE_URL=" + IMAGE_URL);
            e.onNext(IMAGE_URL);
        }
    }).subscribeOn(AndroidSchedulers.from(new Handler().getLooper())).observeOn(Schedulers.io()).map(new Function<String, Bitmap>() {

        @Override
        public Bitmap apply(String s) throws Exception {
            L.i("s=" + s);
            return getBitmap(s);
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Bitmap>() {

        @Override
        public void accept(Bitmap bitmap) throws Exception {
            if (bitmap != null) {
                L.i("bitmap is not null");
                spinKitView.setVisibility(View.GONE);
                imageView.setImageBitmap(bitmap);
            }
        }
    });
}
Also used : Bitmap(android.graphics.Bitmap) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Handler(android.os.Handler) ObservableEmitter(io.reactivex.ObservableEmitter) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 7 with ObservableEmitter

use of io.reactivex.ObservableEmitter in project CloudReader by youlookwhat.

the class RxSaveImage method saveImageAndGetPathObservable.

private static Observable<String> saveImageAndGetPathObservable(Activity context, String url, String title) {
    return Observable.create(new ObservableOnSubscribe<String>() {

        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            // 检查路径
            if (TextUtils.isEmpty(url) || TextUtils.isEmpty(title)) {
                emitter.onError(new Exception("请检查图片路径"));
            }
            // 检查图片是否已存在
            File appDir = new File(Environment.getExternalStorageDirectory(), "云阅相册");
            if (appDir.exists()) {
                File file = new File(appDir, getFileName(url, title));
                if (file.exists()) {
                    emitter.onError(new Exception("图片已存在"));
                }
            }
            // 没有目录创建目录
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            File file = new File(appDir, getFileName(url, title));
            try {
                // 下载
                File fileDo = Glide.with(context).load(url).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
                if (fileDo != null) {
                    // 复制图片
                    copyFile(fileDo.getAbsolutePath(), file.getPath());
                    // 通知图库更新
                    Uri uri = Uri.fromFile(file);
                    Intent scannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                    context.sendBroadcast(scannerIntent);
                } else {
                    emitter.onError(new Exception("无法下载到图片"));
                }
            } catch (Exception e) {
                emitter.onError(e);
            }
            emitter.onNext("");
            emitter.onComplete();
        }
    }).subscribeOn(Schedulers.io());
}
Also used : ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Intent(android.content.Intent) File(java.io.File) Uri(android.net.Uri) ObservableEmitter(io.reactivex.ObservableEmitter) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 8 with ObservableEmitter

use of io.reactivex.ObservableEmitter in project RxCache by VictorAlbertos.

the class ProcessorProvidersTest method getSubscriberCompleted.

private TestObserver getSubscriberCompleted(boolean hasCache, final boolean evictCache, boolean detailResponse, Loader loader, boolean useExpiredDataIfLoaderNotAvailable) {
    Observable observable;
    switch(loader) {
        case VALID:
            observable = Observable.just(new Mock("message"));
            break;
        case NULL:
            observable = Observable.error(new RuntimeException("No data"));
            break;
        default:
            observable = Observable.create(new ObservableOnSubscribe<Object>() {

                @Override
                public void subscribe(ObservableEmitter<Object> e) throws Exception {
                    throw new RuntimeException("error");
                }
            });
            break;
    }
    ConfigProvider configProvider = new ConfigProvider("mockKey", null, null, detailResponse, true, false, "", "", observable, new EvictProvider(evictCache));
    if (hasCache)
        twoLayersCacheMock.save("mockKey", "", "", new Mock("message"), configProvider.getLifeTimeMillis(), configProvider.isExpirable(), configProvider.isEncrypted());
    processorProvidersUT = new ProcessorProvidersBehaviour(twoLayersCacheMock, useExpiredDataIfLoaderNotAvailable, evictExpiredRecordsPersistence, getDeepCopy, doMigrations);
    TestObserver observerMock = processorProvidersUT.getData(configProvider).test();
    observerMock.awaitTerminalEvent();
    return observerMock;
}
Also used : ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) ConfigProvider(io.rx_cache2.ConfigProvider) EvictProvider(io.rx_cache2.EvictProvider) Observable(io.reactivex.Observable) ObservableEmitter(io.reactivex.ObservableEmitter) TestObserver(io.reactivex.observers.TestObserver)

Example 9 with ObservableEmitter

use of io.reactivex.ObservableEmitter 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 10 with ObservableEmitter

use of io.reactivex.ObservableEmitter in project MyJapanese by 54wall.

the class GojuonMemoryFragmentModelImpl method getData.

@Override
public void getData(final int category, Consumer<List<GojuonMemory>> consumer) {
    Disposable disposable = Observable.create(new ObservableOnSubscribe<List<GojuonMemory>>() {

        @Override
        public void subscribe(ObservableEmitter<List<GojuonMemory>> emitter) throws Exception {
            List<GojuonMemory> list;
            switch(category) {
                case Constants.GOJUON_MEMORY:
                    list = DBManager.getInstance().getGojuonMemory();
                    break;
                case Constants.GOJUON_CHENGYU:
                    list = DBManager.getInstance().getGojuonChengyu();
                    break;
                default:
                    list = null;
                    break;
            }
            if (list == null) {
                emitter.onError(new Exception());
            } else {
                emitter.onNext(list);
            }
            emitter.onComplete();
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(consumer);
    mCompositeDisposable.add(disposable);
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) GojuonMemory(pri.weiqiang.liyujapanese.mvp.bean.gojuon.GojuonMemory) ObservableEmitter(io.reactivex.ObservableEmitter)

Aggregations

ObservableEmitter (io.reactivex.ObservableEmitter)39 ObservableOnSubscribe (io.reactivex.ObservableOnSubscribe)38 Disposable (io.reactivex.disposables.Disposable)24 IOException (java.io.IOException)7 Observable (io.reactivex.Observable)6 NonNull (io.reactivex.annotations.NonNull)6 File (java.io.File)6 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Intent (android.content.Intent)4 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)4 Consumer (io.reactivex.functions.Consumer)4 Word (pri.weiqiang.liyujapanese.mvp.bean.dic.Word)4 Observer (io.reactivex.Observer)3 Bitmap (android.graphics.Bitmap)2 Uri (android.net.Uri)2 NonNull (android.support.annotation.NonNull)2 OnClick (butterknife.OnClick)2 Progress (com.lzy.okgo.model.Progress)2 FileNotFoundException (java.io.FileNotFoundException)2