Search in sources :

Example 51 with ObservableOnSubscribe

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

the class RxFileDownloadActivity method fileDownload2.

@OnClick(R.id.fileDownload2)
public void fileDownload2(View view) {
    Observable.create(new ObservableOnSubscribe<Progress>() {

        @Override
        public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
            String etString = etUrl.getText().toString();
            String url = TextUtils.isEmpty(etString) ? Urls.URL_DOWNLOAD : etString;
            // 
            OkGo.<File>get(url).headers("aaa", // 
            "111").params("bbb", // 
            "222").execute(new FileCallback() {

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

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

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

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

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

        @Override
        public void onNext(@NonNull Progress 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();
            btnFileDownload2.setText("下载出错");
            showToast(e.getMessage());
        }

        @Override
        public void onComplete() {
            btnFileDownload2.setText("下载完成");
        }
    });
}
Also used : Disposable(io.reactivex.disposables.Disposable) Progress(com.lzy.okgo.model.Progress) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) FileCallback(com.lzy.okgo.callback.FileCallback) NonNull(io.reactivex.annotations.NonNull) File(java.io.File) ObservableEmitter(io.reactivex.ObservableEmitter) OnClick(butterknife.OnClick)

Example 52 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project My-MVP by REBOOTERS.

the class RxJavaBaseActivity method thread.

private void thread() {
    Observable mObservable = Observable.create(new ObservableOnSubscribe() {

        @Override
        public void subscribe(ObservableEmitter e) throws Exception {
            Log.e(TAG, "subscribe: currentThreadName==" + Thread.currentThread().getName());
            sb.append("\nsubscribe: currentThreadName==" + Thread.currentThread().getName());
            e.onNext("1000");
        }
    });
    Consumer mObserver = new Consumer<String>() {

        @Override
        public void accept(String s) throws Exception {
            Log.e(TAG, "accept: currentThreadName==" + Thread.currentThread().getName());
            Log.e(TAG, "accept: s=" + s);
            sb.append("\naccept: currentThreadName==" + Thread.currentThread().getName());
            logContent.setText(sb.toString());
        }
    };
    mObservable.subscribe(mObserver);
}
Also used : ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Consumer(io.reactivex.functions.Consumer) Observable(io.reactivex.Observable) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 53 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project BestPracticeApp by pop1234o.

the class RxJavaSample method observable.

// endregion
// region 创建操作
// https://github.com/ReactiveX/RxJava/wiki/Creating-Observables (各种创建操作符示例)
/**
 * https://github.com/ReactiveX/RxJava/wiki/Creating-Observables (各种创建操作符示例)
 * create
 * defer
 * empty
 * error
 * from  fromIterable - 遍历collection
 * generate
 * interval
 * just
 * never
 * range
 * timer
 */
private void observable() {
    ObservableJust.just("").map(new Function<String, Integer>() {

        @Override
        public Integer apply(String s) throws Exception {
            return null;
        }
    }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Exception {
        }
    });
    // ==========================================
    Observable.create(new ObservableOnSubscribe<String>() {

        // 当有观察者订阅了我的(Observable)消息
        @Override
        public void subscribe(ObservableEmitter<String> e) throws Exception {
            // 这里是被观察者
            e.onNext("1");
            e.onNext("2");
            if (System.currentTimeMillis() > 0) {
                // 只能调用一次,而且下面的语句不再被接收了
                e.onError(new NullPointerException());
            }
            e.onComplete();
            // onComplete后,不会执行了
            e.onNext(":");
        // 这里执行的线程是 subscribeOn指定的
        }
    }).subscribeOn(Schedulers.io()).observeOn(Schedulers.computation()).map(new Function<String, Integer>() {

        @Override
        public Integer apply(String s) throws Exception {
            // 这里指定的线程是 Schedulers.computation()
            return Integer.parseInt(s);
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {

        private Disposable d;

        @Override
        public void onSubscribe(Disposable d) {
            // Disposable相当于事件对象,用于取消订阅关系???
            this.d = d;
        }

        @Override
        public void onNext(Integer s) {
            // 这个线程是最近一个observeOn指定的
            if ("compelete".equals(s)) {
                // 中断事件流
                d.dispose();
            }
        }

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onComplete() {
        }
    });
    io.reactivex.Observable.create(new ObservableOnSubscribe<Integer>() {

        @Override
        public void subscribe(ObservableEmitter<Integer> e) throws Exception {
            e.onNext(1);
            e.onNext(1);
            e.onNext(1);
            e.onComplete();
            e.onNext(1);
        }
    }).subscribe(new Consumer<Integer>() {

        @Override
        public void accept(Integer integer) throws Exception {
        // 这里只接受onNext中的事件,onComplete后的事件不会接收到
        }
    });
    // 创建List发射器
    Observable.fromIterable(new ArrayList<String>()).subscribe(new Consumer<String>() {

        @Override
        public void accept(String s) throws Exception {
        }
    });
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BiFunction(io.reactivex.functions.BiFunction) Function(io.reactivex.functions.Function) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 54 with ObservableOnSubscribe

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

the class BindAppDataSource 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 = BindAppDataSource.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 55 with ObservableOnSubscribe

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

the class BindAppDataSource 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 = BindAppDataSource.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)

Aggregations

ObservableOnSubscribe (io.reactivex.ObservableOnSubscribe)60 ObservableEmitter (io.reactivex.ObservableEmitter)50 Disposable (io.reactivex.disposables.Disposable)36 Observable (io.reactivex.Observable)14 ArrayList (java.util.ArrayList)12 List (java.util.List)12 SupportSQLiteDatabase (androidx.sqlite.db.SupportSQLiteDatabase)9 File (java.io.File)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