Search in sources :

Example 11 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project Offer by woshiyizhijiao.

the class RxJavaActivity method zip2.

/**
 * 上游两个管道的其中一个在无线发送事件,而另一个管道只发送一个,最终导致oom
 */
public void zip2(View v) {
    Observable observable1 = Observable.create(new ObservableOnSubscribe<Integer>() {

        @Override
        public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
            for (int x = 0; ; x++) {
                emitter.onNext(1);
            }
        }
    }).subscribeOn(Schedulers.io());
    Observable<String> observable2 = Observable.create(new ObservableOnSubscribe<String>() {

        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            emitter.onNext("第二个管道");
        }
    }).subscribeOn(Schedulers.io());
    Observable.zip(observable1, observable2, new BiFunction<Integer, String, String>() {

        /**
         * Calculate a value based on the input values.
         *
         * @param integer the first value
         * @param s       the second value
         * @return the result value
         * @throws Exception on error
         */
        @Override
        public String apply(Integer integer, String s) throws Exception {
            return integer + s;
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer() {

        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onNext(Object value) {
            LogUtils.e("onNext" + value);
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onComplete() {
        }
    });
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Observable(io.reactivex.Observable) Observer(io.reactivex.Observer) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 12 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project CustomViews by AndroidStudy233.

the class RxSchedulerActivity method changeScheduler.

/**
 * 在不指定线程的情况下, RxJava 遵循的是线程不变的原则,即:在哪个线程调用 subscribe(),就在哪个线程生产事件;
 * 在哪个线程生产事件,就在哪个线程消费事件。如果需要切换线程,就需要用到 Scheduler (调度器)。
 * <p>
 * Schedulers.immediate(): 直接在当前线程运行,相当于不指定线程。这是默认的 Scheduler。
 * <p>
 * Schedulers.newThread(): 总是启用新线程,并在新线程执行操作。
 * <p>
 * Schedulers.io(): I/O 操作(读写文件、读写数据库、网络信息交互等)所使用的 Scheduler。
 * 行为模式和 newThread() 差不多,区别在于 io() 的内部实现是是用一个无数量上限的线程池,
 * 可以重用空闲的线程,因此多数情况下 io() 比 newThread() 更有效率。不要把计算工作放在 io() 中,可以避免创建不必要的线程。
 * <p>
 * Schedulers.computation(): 计算所使用的 Scheduler。这个计算指的是 CPU 密集型计算,即不会被 I/O 等操作限制性能的操作,
 * 例如图形的计算。这个 Scheduler 使用的固定的线程池,大小为 CPU 核数。不要把 I/O 操作放在 computation() 中,否则 I/O 操作的等待时间会浪费 CPU。
 * <p>
 * 另外, Android 还有一个专用的 AndroidSchedulers.mainThread(),它指定的操作将在 Android 主线程运行。
 * 有了这几个 Scheduler ,就可以使用 subscribeOn() 和 observeOn() 两个方法来对线程进行控制了。
 * <p>
 * subscribeOn(): 指定 subscribe() 所发生的线程,即 Observable.OnSubscribe 被激活时所处的线程。或者叫做事件产生的线程。 (我的理解是被观察者事件创建))
 * <p>
 * observeOn(): 指定 Subscriber 所运行在的线程。或者叫做事件消费的线程。(我的理解是观察者的事件触发)
 */
@SuppressLint("CheckResult")
public void changeScheduler() {
    Observable.just(1, 2, 3, 4).subscribeOn(// 指定 subscribe() 发生在 IO 线程
    Schedulers.io()).observeOn(// 指定 Subscriber 的回调发生在主线程()
    AndroidSchedulers.mainThread()).subscribe(number -> {
        Log.d("aaa", "number:" + number);
    });
    // doOnSubscribe, 就像subscriber的onstart()方法, 但是onstart不能确定是在哪儿执行的,
    // 所以会有线程问题, 然而doOnSubscribe后面可以指定线程
    // 当然相对应的还有doOnNext().
    Observable.just(1, 2, 3, 4).subscribeOn(Schedulers.io()).doOnSubscribe(disposable -> {
    // 比如有这么个操作需要在主线程执行
    // progressBar.setVisibility(View.VISIBLE);
    }).subscribeOn(// 指定doOnSubscribe的操作在主线程
    AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(integer -> {
    // 比如这里又要隐藏
    // progressBar.setVisibility(View.INVISIBLE);
    });
    Observable.create((ObservableOnSubscribe<Drawable>) emitter -> {
        try {
            Thread.sleep(10 * 1000);
            Drawable drawable = getResources().getDrawable(R.drawable.pic_sample);
            emitter.onNext(drawable);
            emitter.onComplete();
        } catch (InterruptedException e) {
            e.printStackTrace();
            emitter.onError(e);
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Drawable>() {

        @Override
        public void onSubscribe(Disposable d) {
        // 这里的 Disposable 可以用来取消事件
        }

        @Override
        public void onNext(Drawable t) {
            imageView.setImageDrawable(t);
        }

        @Override
        public void onError(Throwable e) {
            Log.e("GG", e.getMessage());
        }

        @Override
        public void onComplete() {
            Log.e("GG", "onCompleted");
        }
    });
}
Also used : Bundle(android.os.Bundle) ButterKnife(butterknife.ButterKnife) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) ImageView(android.widget.ImageView) ObservableEmitter(io.reactivex.ObservableEmitter) Drawable(android.graphics.drawable.Drawable) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) AppCompatActivity(android.support.v7.app.AppCompatActivity) BindView(butterknife.BindView) SuppressLint(android.annotation.SuppressLint) Disposable(io.reactivex.disposables.Disposable) Observer(io.reactivex.Observer) Observable(io.reactivex.Observable) Schedulers(io.reactivex.schedulers.Schedulers) R(com.shiqkuangsan.rxandroidmvp.R) Log(android.util.Log) Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Drawable(android.graphics.drawable.Drawable) SuppressLint(android.annotation.SuppressLint)

Example 13 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project RxTools by vondear.

the class RxCameraTool method takePic.

public static void takePic(Context mContext, final RxCameraView mCameraView) {
    try {
        if (mCameraView.isCameraOpened()) {
            RxVibrateTool.vibrateOnce(mContext, 150);
            RxToast.normal("正在拍照..");
            try {
                mCameraView.takePicture();
            } catch (Exception var2) {
                RxToast.normal("你碰到问题咯");
            }
        } else {
            mCameraView.start();
            RxVibrateTool.vibrateOnce(mContext, 150);
            RxToast.normal("正在拍照..");
            Observable.create(new ObservableOnSubscribe<Integer>() {

                @Override
                public void subscribe(@NonNull ObservableEmitter<Integer> e) {
                    // 延时
                    SystemClock.sleep(500);
                    e.onNext(1);
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {

                // 第二步:初始化Observer
                private Disposable mDisposable;

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

                @Override
                public void onNext(@NonNull Integer integer) {
                    switch(integer) {
                        case 1:
                            try {
                                mCameraView.takePicture();
                            } catch (Exception var2) {
                                RxToast.normal("你碰到问题咯");
                            }
                            break;
                        default:
                            break;
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                }

                @Override
                public void onComplete() {
                }
            });
        }
    } catch (Exception var3) {
        RxToast.normal("你碰到了问题咯");
    }
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) NonNull(io.reactivex.annotations.NonNull) IOException(java.io.IOException) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 14 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project RxTools by vondear.

the class RxCameraTool method initCameraEvent.

public static void initCameraEvent(final Context mContext, final RxCameraView mCameraView, final byte[] data, final String fileDir, final String picName, final double mLongitude, final double mLatitude, final boolean isEconomize, final OnRxCamera onRxCamera) {
    onRxCamera.onBefore();
    Observable.create(new ObservableOnSubscribe<Integer>() {

        @Override
        public void subscribe(@NonNull final ObservableEmitter<Integer> e) {
            File fileParent = new File(fileDir);
            File cacheParent = new File(RxConstants.PICTURE_CACHE_PATH);
            if (!cacheParent.exists()) {
                cacheParent.mkdirs();
            }
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            final File cachefile = new File(cacheParent, picName);
            final File compressFile = new File(fileParent, picName);
            OutputStream os = null;
            try {
                os = new FileOutputStream(cachefile);
                os.write(data);
                os.close();
                RxMagic.createBuilder(mContext).load(cachefile).setCompressListener(new OnCompressListener() {

                    @Override
                    public void onStart() {
                        TLog.d("图片压缩", "开始压缩");
                    }

                    @Override
                    public void onSuccess(File file) {
                        if (RxFileTool.copyOrMoveFile(file, compressFile, true)) {
                            TLog.d("图片压缩", "压缩完成");
                            onRxCamera.onSuccessCompress(compressFile);
                            if (mLongitude != 0 || mLatitude != 0) {
                                RxExifTool.writeLatLonIntoJpeg(compressFile.getAbsolutePath(), mLatitude, mLongitude);
                                onRxCamera.onSuccessExif(compressFile);
                                e.onNext(2);
                            } else {
                                e.onNext(3);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        TLog.d("图片压缩", "压缩异常");
                    // Logger.d(e);
                    }
                }).launch();
            } catch (IOException e1) {
                TLog.w("onPictureTaken", "Cannot write to " + compressFile, e1);
            } finally {
                if (os != null) {
                    try {
                        os.close();
                        e.onNext(1);
                    } catch (IOException e2) {
                    // Ignore
                    }
                }
            }
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {

        // 第二步:初始化Observer
        private Disposable mDisposable;

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

        @Override
        public void onNext(@NonNull Integer integer) {
            switch(integer) {
                case 1:
                    try {
                        if (isEconomize) {
                            mCameraView.stop();
                        }
                    } catch (Exception e) {
                    }
                    break;
                case 2:
                    RxToast.normal("拍照成功");
                    break;
                case 3:
                    RxToast.error("请先获取定位信息");
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onError(@NonNull Throwable e) {
        }

        @Override
        public void onComplete() {
        }
    });
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) OnCompressListener(com.tamsiree.rxkit.photomagic.OnCompressListener) IOException(java.io.IOException) IOException(java.io.IOException) NonNull(io.reactivex.annotations.NonNull) FileOutputStream(java.io.FileOutputStream) File(java.io.File) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 15 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project LiYuJapanese by 54wall.

the class SplashActivity method initData.

private void initData() {
    // 预加载数据库,音频与GIF资源(GIF资源觉得可以放在后边)
    Disposable disposable = Observable.create(new ObservableOnSubscribe<String>() {

        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            emitter.onNext(ResourceUtils.getString(SplashActivity.this, R.string.loading_data));
            DBManager.getInstance().init();
            GifManager.getInstance().init();
            // SoundPoolManager.init考虑后续变为异步处理进入五十音图在启动
            SoundPoolManager.getInstance().init();
            emitter.onNext(ResourceUtils.getString(SplashActivity.this, R.string.loading_data_success));
            emitter.onComplete();
            // 添加有米广告需要屏蔽下两行代码
            // Thread.sleep(1000);
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            finish();
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {

        @Override
        public void accept(String s) throws Exception {
            mTextView.setText(s);
        }
    });
    addDisposable(disposable);
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Intent(android.content.Intent) ObservableEmitter(io.reactivex.ObservableEmitter)

Aggregations

ObservableOnSubscribe (io.reactivex.ObservableOnSubscribe)64 ObservableEmitter (io.reactivex.ObservableEmitter)54 Disposable (io.reactivex.disposables.Disposable)36 Observable (io.reactivex.Observable)14 ArrayList (java.util.ArrayList)12 List (java.util.List)12 File (java.io.File)11 SupportSQLiteDatabase (androidx.sqlite.db.SupportSQLiteDatabase)9 NonNull (io.reactivex.annotations.NonNull)8 IOException (java.io.IOException)8 Intent (android.content.Intent)7 Observer (io.reactivex.Observer)7 Consumer (io.reactivex.functions.Consumer)7 Bitmap (android.graphics.Bitmap)6 Bundle (android.os.Bundle)6 OnClick (butterknife.OnClick)6 Uri (android.net.Uri)5 View (android.view.View)5 BindView (butterknife.BindView)5 HashMap (java.util.HashMap)5