Search in sources :

Example 1 with ObservableOnSubscribe

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

Example 3 with ObservableOnSubscribe

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

use of io.reactivex.ObservableOnSubscribe in project SmartCampus by Vegen.

the class ArticleDetailPresenter method getNewsContent.

@Override
public void getNewsContent(String url) {
    Disposable disposable = Observable.create((ObservableOnSubscribe<Document>) e -> {
        Document document = Jsoup.connect(url).get();
        e.onNext(document);
        e.onComplete();
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(document -> {
        Element body = document.body();
        // 带有href属性的a元素
        Elements links = body.select("a[href]");
        for (Element element : links) {
            element.attr("href", "");
        }
        Element author = body.select("#author").first();
        Element contentbody = body.select("#contentbody").first();
        Element showtag = body.select("#showtag").last();
        if (mView != null) {
            mView.showNewsContent("</br>" + (author.html() + contentbody.html() + showtag.html()).replace("font-size: 10.5pt", "font-size: 16.5pt").replace("FONT-SIZE: 10.5pt", "FONT-SIZE: 16.5pt").replace("src=\"/files", "src=\"" + Url.ROOT_URL + "/files").replace("href=\"\"", "").replace("【点击:", "【点击:" + SystemUtils.getRandom(5, 30)).replace("发布时间", "</br>发布时间"));
            mView.hideLoading(false);
        }
    }, throwable -> {
        if (mView != null) {
            mView.showMessage(HttpError.getErrorMessage(throwable));
            mView.hideLoading(true);
        }
    });
    mHttpLinkers.add(new DisposableHolder(disposable));
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Element(org.jsoup.nodes.Element) DisposableHolder(com.vegen.smartcampus.baseframework.network.DisposableHolder) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements)

Example 5 with ObservableOnSubscribe

use of io.reactivex.ObservableOnSubscribe in project SmartCampus by Vegen.

the class EmploymentArticleDetailPresenter method getEmploymentList.

@Override
public void getEmploymentList(String url, int type) {
    Disposable disposable = Observable.create((ObservableOnSubscribe<Document>) e -> {
        Document document = Jsoup.connect(url).get();
        e.onNext(document);
        e.onComplete();
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(document -> {
        Element body = document.body();
        if (mView != null) {
            mView.showEmploymentList(filterData(body, type));
            mView.hideLoading(false);
            if (type == Constant.FAIR)
                mView.loadMoreEnd(true);
        }
    }, throwable -> {
        if (mView != null) {
            mView.showMessage(HttpError.getErrorMessage(throwable));
            mView.hideLoading(true);
        }
    });
    mHttpLinkers.add(new DisposableHolder(disposable));
}
Also used : Disposable(io.reactivex.disposables.Disposable) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Element(org.jsoup.nodes.Element) DisposableHolder(com.vegen.smartcampus.baseframework.network.DisposableHolder) Document(org.jsoup.nodes.Document)

Aggregations

ObservableOnSubscribe (io.reactivex.ObservableOnSubscribe)39 ObservableEmitter (io.reactivex.ObservableEmitter)27 Disposable (io.reactivex.disposables.Disposable)19 Observable (io.reactivex.Observable)12 List (java.util.List)11 ArrayList (java.util.ArrayList)8 IOException (java.io.IOException)7 Document (org.jsoup.nodes.Document)7 Element (org.jsoup.nodes.Element)7 File (java.io.File)6 Intent (android.content.Intent)5 Bundle (android.os.Bundle)5 NonNull (android.support.annotation.NonNull)5 HashMap (java.util.HashMap)5 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)4 Nullable (android.support.annotation.Nullable)4 DisposableHolder (com.vegen.smartcampus.baseframework.network.DisposableHolder)4 Map (java.util.Map)4 Log (android.util.Log)3 AndroidSchedulers (io.reactivex.android.schedulers.AndroidSchedulers)3