Search in sources :

Example 1 with ObservableEmitter

use of io.reactivex.ObservableEmitter in project simple-stack by Zhuinden.

the class Chat method getMessages.

public Observable<Message> getMessages() {
    return Observable.create(new ObservableOnSubscribe<Message>() {

        @Override
        public void subscribe(@NonNull ObservableEmitter<Message> emitter) throws Exception {
            final Random random = new Random();
            while (true) {
                if (random.nextInt(PROBABILITY) == 0) {
                    try {
                        User from = users.get(random.nextInt(users.size()));
                        Response<Quotes> response = chats.service.getQuote().execute();
                        Quotes quotes = response.body();
                        if (quotes == null) {
                            throw new Exception("Could not download quotes [" + response.errorBody().string() + "] ");
                        }
                        Quote quote = quotes.getContents().getQuotes().get(0);
                        Message next = new Message(from, quote.getQuote());
                        messages.add(next);
                        if (!emitter.isDisposed()) {
                            emitter.onNext(next);
                        }
                    } catch (Exception e) {
                        if (!emitter.isDisposed()) {
                            emitter.onError(e);
                            break;
                        }
                    }
                }
                try {
                    // Hijacking the thread like this is sleazey, but you get the idea.
                    Thread.sleep(SLEEP_MILLIS);
                } catch (InterruptedException e) {
                    if (!emitter.isDisposed()) {
                        emitter.onError(e);
                    }
                    break;
                }
            }
        }
    }).startWith(//
    messages).subscribeOn(//
    Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
Also used : Quote(com.example.mortar.model.quotes.Quote) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Random(java.util.Random) NonNull(io.reactivex.annotations.NonNull) Quotes(com.example.mortar.model.quotes.Quotes) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 2 with ObservableEmitter

use of io.reactivex.ObservableEmitter 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.yuchengren.mvp.entity.People) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 3 with ObservableEmitter

use of io.reactivex.ObservableEmitter in project Mvp-Rxjava-Retrofit-dagger2 by pengMaster.

the class SplashPresenter method toActDownLoadNetKey.

/**
 * 下载网络请求验证码
 */
private void toActDownLoadNetKey() {
    ThreadUtils.runThread(new Runnable() {

        @Override
        public void run() {
            HttpClient httpClient = new HttpClient();
            Map<String, String> msg = new HashMap<String, String>();
            msg.put("appKey", "9c3d77f18e4848d095e626e9b3a009a3");
            msg.put("appSecret", "ff265c879c4ac08028e77a6c66078f9ce81c15b6fbc76c18f7a12a97c859c92b");
            String params = new Gson().toJson(msg);
            StringRequestEntity paramEntity = null;
            try {
                paramEntity = new StringRequestEntity(params, "application/json", "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            PostMethod postMethod = new PostMethod(Api.POST_KEY);
            postMethod.setRequestEntity(paramEntity);
            try {
                httpClient.executeMethod(postMethod);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                InputStream inputStream = postMethod.getResponseBodyAsStream();
                final String resultKey = convertStreamToString(inputStream);
                ThreadUtils.runInMainThread(new Runnable() {

                    @Override
                    public void run() {
                        ResultKeyGsonBean resultKeyBean = new Gson().fromJson(resultKey, ResultKeyGsonBean.class);
                        String access_token = resultKeyBean.getData().getAccess_token();
                        GlobalConstantUtils.setToken(access_token);
                        Observable.create(new ObservableOnSubscribe<String>() {

                            @Override
                            public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                                SystemClock.sleep(2000);
                                e.onNext("");
                                e.onComplete();
                            }
                        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {

                            @Override
                            public void accept(String s) throws Exception {
                                Intent intent = new Intent(AppLifecyclesImpl.mAppContext, MainActivity.class);
                                mRootView.launchActivity(intent);
                                mRootView.killMyself();
                            }
                        });
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) PostMethod(org.apache.commons.httpclient.methods.PostMethod) InputStream(java.io.InputStream) Gson(com.google.gson.Gson) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Intent(android.content.Intent) IOException(java.io.IOException) MainActivity(com.mtm.mrecord.mvp.ui.activity.MainActivity) ResultKeyGsonBean(com.mtm.mrecord.mvp.model.entity.ResultKeyGsonBean) LoginException(javax.security.auth.login.LoginException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HttpClient(org.apache.commons.httpclient.HttpClient) NonNull(io.reactivex.annotations.NonNull) Map(java.util.Map) HashMap(java.util.HashMap) ObservableEmitter(io.reactivex.ObservableEmitter)

Example 4 with ObservableEmitter

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

use of io.reactivex.ObservableEmitter 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) {
            boolean needToOpened = !BindKripton180BeanInsertSelectDataSource.this.isOpenInWriteMode();
            boolean success = false;
            @SuppressWarnings("resource") SQLiteDatabase connection = needToOpened ? openWritableDatabase() : database();
            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) {
                }
                if (needToOpened) {
                    close();
                }
                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 : ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) 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