Search in sources :

Example 31 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project kripton by xcesco.

the class BindKripton180BeanInsertSelectDataSource method execute.

public <T> Observable<T> execute(final ObservableTransaction<T> transaction) {
    ObservableOnSubscribe<T> emitter = new ObservableOnSubscribe<T>() {

        @Override
        public void subscribe(ObservableEmitter<T> emitter) {
            // open database in thread safe mode
            Pair<Boolean, SupportSQLiteDatabase> _status = BindKripton180BeanInsertSelectDataSource.this.openDatabaseThreadSafeMode(true);
            boolean success = false;
            SupportSQLiteDatabase connection = _status.value1;
            DataSourceSingleThread currentDaoFactory = _daoFactorySingleThread.bindToThread();
            currentDaoFactory.onSessionOpened();
            try {
                connection.beginTransaction();
                if (transaction != null && TransactionResult.COMMIT == transaction.onExecute(currentDaoFactory, emitter)) {
                    connection.setTransactionSuccessful();
                    success = true;
                }
                emitter.onComplete();
            } catch (Throwable e) {
                Logger.error(e.getMessage());
                e.printStackTrace();
                emitter.onError(e);
                currentDaoFactory.onSessionClear();
            } finally {
                try {
                    connection.endTransaction();
                } catch (Throwable e) {
                }
                // close database in thread safe mode
                closeThreadSafeMode(_status);
                if (success) {
                    currentDaoFactory.onSessionClosed();
                } else {
                    currentDaoFactory.onSessionClear();
                }
            }
            return;
        }
    };
    Observable<T> result = Observable.create(emitter);
    if (globalSubscribeOn != null)
        result.subscribeOn(globalSubscribeOn);
    if (globalObserveOn != null)
        result.observeOn(globalObserveOn);
    return result;
}
Also used : SupportSQLiteDatabase(androidx.sqlite.db.SupportSQLiteDatabase) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 32 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project XRichText by sendtion.

the class NewActivity method insertImagesSync.

/**
 * 异步方式插入图片
 */
private void insertImagesSync(final Intent data) {
    insertDialog.show();
    Observable.create(new ObservableOnSubscribe<String>() {

        @Override
        public void subscribe(ObservableEmitter<String> emitter) {
            try {
                et_new_content.measure(0, 0);
                List<Uri> mSelected = Matisse.obtainResult(data);
                // 可以同时插入多张图片
                for (Uri imageUri : mSelected) {
                    String imagePath = SDCardUtil.getFilePathFromUri(NewActivity.this, imageUri);
                    // Log.e(TAG, "###path=" + imagePath);
                    // 压缩图片
                    Bitmap bitmap = ImageUtils.getSmallBitmap(imagePath, screenWidth, screenHeight);
                    // bitmap = BitmapFactory.decodeFile(imagePath);
                    imagePath = SDCardUtil.saveToSdCard(bitmap);
                    // Log.e(TAG, "###imagePath="+imagePath);
                    emitter.onNext(imagePath);
                }
                // 测试插入网络图片 http://pics.sc.chinaz.com/files/pic/pic9/201904/zzpic17414.jpg
                // emitter.onNext("http://pics.sc.chinaz.com/files/pic/pic9/201903/zzpic16838.jpg");
                emitter.onNext("http://b.zol-img.com.cn/sjbizhi/images/10/640x1136/1572123845476.jpg");
                emitter.onNext("https://img.ivsky.com/img/tupian/pre/201903/24/richu_riluo-013.jpg");
                emitter.onComplete();
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(e);
            }
        }
    }).subscribeOn(// 生产事件在io
    Schedulers.io()).observeOn(// 消费事件在UI线程
    AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {

        @Override
        public void onComplete() {
            if (insertDialog != null && insertDialog.isShowing()) {
                insertDialog.dismiss();
            }
            showToast("图片插入成功");
        }

        @Override
        public void onError(Throwable e) {
            if (insertDialog != null && insertDialog.isShowing()) {
                insertDialog.dismiss();
            }
            showToast("图片插入失败:" + e.getMessage());
        }

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

        @Override
        public void onNext(String imagePath) {
            et_new_content.insertImage(imagePath);
        }
    });
}
Also used : Disposable(io.reactivex.disposables.Disposable) Bitmap(android.graphics.Bitmap) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Uri(android.net.Uri) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 33 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe 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 34 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project GzuClassSchedule by mnnyang.

the class ImptPresenter method parseCoursesHtmlToDb.

private void parseCoursesHtmlToDb(final String html, final String courseTimeTerm) {
    try {
        Observable.create(new ObservableOnSubscribe<String>() {

            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                ArrayList<CourseV2> courseV2s = ParseCourse.parse(html);
                // 删除旧数据
                CourseGroup group = Cache.instance().getCourseGroupDao().queryBuilder().where(CourseGroupDao.Properties.CgName.eq(courseTimeTerm)).unique();
                CourseV2Dao courseV2Dao = Cache.instance().getCourseV2Dao();
                if (null != group) {
                    courseV2Dao.queryBuilder().where(CourseV2Dao.Properties.CouCgId.eq(group.getCgId())).buildDelete().executeDeleteWithoutDetachingEntities();
                } else {
                    // 不存在旧数据 创建新的课表组
                    group = new CourseGroup();
                    group.setCgName(courseTimeTerm);
                    Cache.instance().getCourseGroupDao().insert(group);
                }
                for (CourseV2 courseV2 : courseV2s) {
                    courseV2.setCouCgId(group.getCgId());
                    courseV2Dao.insert(courseV2);
                }
                emitter.onNext("导入成功");
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {

            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(String s) {
                if (mImptView == null) {
                    // view被销毁
                    return;
                }
                LogUtil.i(this, "导入成功:" + courseTimeTerm);
                Long curGroupId = Cache.instance().getCourseGroupDao().queryBuilder().where(CourseGroupDao.Properties.CgName.eq(courseTimeTerm)).unique().getCgId();
                Preferences.putLong(app.mContext.getString(R.string.app_preference_current_cs_name_id), curGroupId);
                mImptView.hideImpting();
                mImptView.showSucceed();
            }

            @Override
            public void onError(Throwable e) {
                if (mImptView == null) {
                    // view被销毁
                    return;
                }
                e.printStackTrace();
                mImptView.hideImpting();
                mImptView.showErrToast("插入数据库失败", true);
            }

            @Override
            public void onComplete() {
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
        mImptView.hideImpting();
        mImptView.showErrToast("导入错误", true);
    }
}
Also used : Disposable(io.reactivex.disposables.Disposable) CourseV2Dao(com.mnnyang.gzuclassschedule.data.greendao.CourseV2Dao) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) CourseGroup(com.mnnyang.gzuclassschedule.data.beanv2.CourseGroup) CourseV2(com.mnnyang.gzuclassschedule.data.beanv2.CourseV2) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 35 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project AndroidQuick by ddnosh.

the class RxJavaFragment method testCreate.

// --------Create
private void testCreate() {
    Observable.create(new ObservableOnSubscribe<String>() {

        @Override
        public void subscribe(ObservableEmitter<String> e) {
            e.onNext("1");
            e.onNext("");
            e.onNext("2");
            e.onComplete();
        // e.onError(new NullPointerException());
        }
    }).subscribe(new Observer<String>() {

        // 主动阻断本次和后面的所有订阅
        private Disposable disposable;

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

        @Override
        public void onNext(String s) {
            System.out.println("RxJava:" + s);
            if (StringUtil.isEmpty(s)) {
                // s为空不符合条件, 阻断本次和后面的所有订阅
                disposable.dispose();
            }
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onComplete() {
            ToastUtil.showToast("create done!");
        }
    });
    Observable.create(emitter -> {
        LogUtil.d(TAG, "【开始create】");
        emitter.onNext("【begin!!!】");
        emitter.onComplete();
        LogUtil.d(TAG, "【结束create】");
    }).doOnNext(s -> LogUtil.d(TAG, "【doOnNext】")).doOnError(e -> LogUtil.d(TAG, "【doOnError】")).doOnComplete(() -> LogUtil.d(TAG, "【doOnComplete】")).doOnSubscribe(disposable -> LogUtil.d(TAG, "【doOnSubscribe】")).doFinally(() -> LogUtil.d(TAG, "【doFinally】")).subscribe(o -> LogUtil.d(TAG, "【onNext】"), e -> LogUtil.d(TAG, "【onError】"), () -> LogUtil.d(TAG, "【onComplete】"), d -> LogUtil.d(TAG, "【onSubscribe】"));
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) BiFunction(io.reactivex.functions.BiFunction) Arrays(java.util.Arrays) Bundle(android.os.Bundle) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Date(java.util.Date) Uri(android.net.Uri) ImageView(android.widget.ImageView) ApiException(com.androidwind.androidquick.module.exception.ApiException) TagInfo(com.androidwind.annotation.annotation.TagInfo) LifecycleProvider(com.trello.rxlifecycle2.LifecycleProvider) LogUtil(com.androidwind.androidquick.util.LogUtil) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) OnClick(butterknife.OnClick) BindView(butterknife.BindView) Locale(java.util.Locale) View(android.view.View) Schedulers(io.reactivex.schedulers.Schedulers) Log(android.util.Log) R(com.androidwind.androidquick.demo.R) BaseObserver(com.androidwind.androidquick.module.rxjava.BaseObserver) FlowableEmitter(io.reactivex.FlowableEmitter) ObservableEmitter(io.reactivex.ObservableEmitter) AndroidLifecycle(com.trello.lifecycle2.android.lifecycle.AndroidLifecycle) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) TextView(android.widget.TextView) DisposableObserver(io.reactivex.observers.DisposableObserver) ToastUtil(com.androidwind.androidquick.util.ToastUtil) PublishSubject(io.reactivex.subjects.PublishSubject) AssetsUtil(com.androidwind.androidquick.demo.tool.AssetsUtil) NotNull(org.jetbrains.annotations.NotNull) Context(android.content.Context) BiConsumer(io.reactivex.functions.BiConsumer) Environment(android.os.Environment) StringUtil(com.androidwind.androidquick.util.StringUtil) SimpleDateFormat(java.text.SimpleDateFormat) Intent(android.content.Intent) BitmapFactory(android.graphics.BitmapFactory) SystemClock(android.os.SystemClock) Callable(java.util.concurrent.Callable) ArrayList(java.util.ArrayList) Lifecycle(androidx.lifecycle.Lifecycle) BindTag(com.androidwind.annotation.annotation.BindTag) Flowable(io.reactivex.Flowable) ObservableSource(io.reactivex.ObservableSource) Observable(io.reactivex.Observable) Subscriber(org.reactivestreams.Subscriber) GlideUtils(com.androidwind.androidquick.demo.tool.GlideUtils) BaseFragment(com.androidwind.androidquick.demo.base.BaseFragment) Subject(io.reactivex.subjects.Subject) BackpressureStrategy(io.reactivex.BackpressureStrategy) Action(io.reactivex.functions.Action) RxUtil(com.androidwind.androidquick.demo.tool.RxUtil) Target(com.bumptech.glide.request.target.Target) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) Consumer(io.reactivex.functions.Consumer) File(java.io.File) FlowableOnSubscribe(io.reactivex.FlowableOnSubscribe) Glide(com.bumptech.glide.Glide) Bitmap(android.graphics.Bitmap) Function(io.reactivex.functions.Function) Subscription(org.reactivestreams.Subscription) Observer(io.reactivex.Observer) WebViewActivity(com.androidwind.androidquick.demo.features.function.ui.webview.WebViewActivity) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) 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