Search in sources :

Example 26 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project MVP by yuchengren.

the class RxAndroidActivity method test2.

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

        @Override
        public void subscribe(ObservableEmitter<String> e) throws Exception {
            // IO线程中做网络访问等耗时操作
            // String responseJsonString = OkHttpUtil.get("http://192.168.0.1:8080/TradeType=getPeoples");
            // String responseJsonString = "[{\"gendar\":29,\"name\":\"ren\",\"sex\":0},{\"gendar\":30,\"name\":\"ling\",\"sex\":1}]";
            List<People> peopleList = new ArrayList<>();
            peopleList.add(new People("ren", 0, 29));
            peopleList.add(new People("ling", 1, 30));
            LogHelper.e(TAG, GsonUtil.formatObjectToJson(peopleList));
            e.onNext(GsonUtil.formatObjectToJson(peopleList));
        }
    }).map(new Function<String, List<People>>() {

        @Override
        public List<People> apply(String s) throws Exception {
            LogHelper.d(TAG, "map,CurrentThreadName=" + Thread.currentThread().getName());
            List<People> peopleList = GsonUtil.parseJsonToList(s, People.class);
            // json解析成实体类
            return peopleList;
        }
    }).doOnNext(new Consumer<List<People>>() {

        @Override
        public void accept(List<People> people) throws Exception {
            LogHelper.d(TAG, "doOnNext,CurrentThreadName=" + Thread.currentThread().getName());
        // 存入数据库
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<List<People>>() {

        @Override
        public void accept(List<People> people) throws Exception {
        // 主线程中刷新页面
        }
    });
}
Also used : ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Consumer(io.reactivex.functions.Consumer) People(com.ycr.module.base.entity.People) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 27 with ObservableOnSubscribe

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

the class RxJavaBaseActivity method basicRxjava2.

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

        @Override
        public void subscribe(ObservableEmitter e) throws Exception {
            e.onNext("1");
            e.onNext("2");
            e.onNext("3");
            e.onNext("4");
            e.onComplete();
        }
    });
    Observer mObserver = new Observer() {

        @Override
        public void onSubscribe(Disposable d) {
            Log.e(TAG, "onSubscribe: d=" + d);
            sb.append("\nonSubcribe: d=" + d);
        }

        @Override
        public void onNext(Object s) {
            Log.e(TAG, "onNext: " + s);
            sb.append("\nonNext: " + s);
        }

        @Override
        public void onError(Throwable e) {
            Log.e(TAG, "onError: " + e);
            sb.append("\nonError: " + e.toString());
            logContent.setText(sb.toString());
        }

        @Override
        public void onComplete() {
            Log.e(TAG, "onComplete");
            sb.append("\nonComplete: ");
            logContent.setText(sb.toString());
        }
    };
    mObservable.subscribe(mObserver);
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Observer(io.reactivex.Observer) Observable(io.reactivex.Observable) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 28 with ObservableOnSubscribe

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

the class RxJavaBaseActivity method withRetrofit2.

private void withRetrofit2() {
    OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
    mBuilder.readTimeout(10, TimeUnit.SECONDS);
    mBuilder.connectTimeout(30, TimeUnit.SECONDS);
    HttpLoggingInterceptor mLoggingInterceptor = new HttpLoggingInterceptor();
    mLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    mBuilder.addInterceptor(mLoggingInterceptor);
    OkHttpClient mClient = mBuilder.build();
    Retrofit.Builder builder = new Retrofit.Builder();
    builder.baseUrl(BASE_URL);
    builder.client(mClient);
    Retrofit mRetrofit = builder.build();
    final GankApi mGankApi = mRetrofit.create(GankApi.class);
    final Call<ResponseBody> mCall = mGankApi.getJson("10/1");
    Observable.create((ObservableOnSubscribe<ResponseBody>) e -> e.onNext(mCall.execute().body())).map(ResponseBody::string).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {

        @Override
        public void onSubscribe(Disposable d) {
            Log.e(TAG, "onSubscribe: d=" + d);
        }

        @Override
        public void onNext(String s) {
            logContent.setText(s);
        }

        @Override
        public void onError(Throwable e) {
            logContent.setText(e.toString());
        }

        @Override
        public void onComplete() {
        }
    });
}
Also used : Bundle(android.os.Bundle) R2(home.smart.fly.http.R2) ButterKnife(butterknife.ButterKnife) SimpleRequestTransformer(home.smart.fly.transformer.SimpleRequestTransformer) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Completable(io.reactivex.Completable) AndroidSchedulers(io.reactivex.android.schedulers.AndroidSchedulers) OnClick(butterknife.OnClick) BindView(butterknife.BindView) SuppressLint(android.annotation.SuppressLint) Toast(android.widget.Toast) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) View(android.view.View) Button(android.widget.Button) CompletableEmitter(io.reactivex.CompletableEmitter) Observable(io.reactivex.Observable) Schedulers(io.reactivex.schedulers.Schedulers) Log(android.util.Log) ResponseBody(okhttp3.ResponseBody) R(home.smart.fly.http.R) RxAppCompatActivity(com.trello.rxlifecycle2.components.support.RxAppCompatActivity) GankAndroid(home.smart.fly.http.model.GankAndroid) CompletableObserver(io.reactivex.CompletableObserver) RxJavaPlugins(io.reactivex.plugins.RxJavaPlugins) Consumer(io.reactivex.functions.Consumer) Retrofit(retrofit2.Retrofit) TimeUnit(java.util.concurrent.TimeUnit) RxJava2CallAdapterFactory(com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) ApiGenerator(home.smart.fly.proxy.ApiGenerator) Observer(io.reactivex.Observer) SimpleRequestResponseTransformer(home.smart.fly.transformer.SimpleRequestResponseTransformer) GankApi(home.smart.fly.http.model.GankApi) Call(retrofit2.Call) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) OkHttpClient(okhttp3.OkHttpClient) GankApi(home.smart.fly.http.model.GankApi) ResponseBody(okhttp3.ResponseBody) Retrofit(retrofit2.Retrofit) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor)

Example 29 with ObservableOnSubscribe

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

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