io.reactivex.FlowableOnSubscribe Java Examples

The following examples show how to use io.reactivex.FlowableOnSubscribe. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ActorMessageFlowable.java    From actor4j-core with Apache License 2.0 6 votes vote down vote up
public static Flowable<ActorMessage<?>> getMessages(final Queue<ActorMessage<?>> stash) {
	return Flowable.create(new FlowableOnSubscribe<ActorMessage<?>>() {
		@Override
		public void subscribe(FlowableEmitter<ActorMessage<?>> emitter) throws Exception {
			try {
				ActorMessage<?> message;
				for (int i=0; !emitter.isCancelled() && i<emitter.requested() && (message=stash.poll())!=null; i++) 
					emitter.onNext(message);
				
				if (emitter.isCancelled())
					return;
				else
					emitter.onComplete();;
			}
			catch (Exception e) {
				emitter.onError(e);
			}
		}
		
	}, BackpressureStrategy.BUFFER);
}
 
Example #2
Source File: FirebaseInAppMessagingFlowableTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private static TestSubscriber<InAppMessage> listenerToFlowable(FirebaseInAppMessaging instance) {
  Flowable<InAppMessage> listenerFlowable =
      Flowable.create(
          new FlowableOnSubscribe<InAppMessage>() {
            @Override
            public void subscribe(FlowableEmitter<InAppMessage> emitter) throws Exception {
              instance.setMessageDisplayComponent(
                  new FirebaseInAppMessagingDisplay() {
                    @Override
                    public void displayMessage(
                        InAppMessage inAppMessage,
                        FirebaseInAppMessagingDisplayCallbacks callbacks) {
                      emitter.onNext(inAppMessage);
                      Log.i("FIAM", "Putting callback for IAM " + inAppMessage.getCampaignName());
                      callbacksHashMap.put(inAppMessage.getCampaignId(), callbacks);
                    }
                  });
            }
          },
          BUFFER);
  return listenerFlowable.test();
}
 
Example #3
Source File: ChoiceCityActivity.java    From SeeWeather with Apache License 2.0 6 votes vote down vote up
/**
 * 查询全国所有的省,从数据库查询
 */
private void queryProvinces() {
    getToolbar().setTitle("选择省份");
    Flowable.create((FlowableOnSubscribe<String>) emitter -> {
        if (provincesList.isEmpty()) {
            provincesList.addAll(WeatherDB.loadProvinces(DBManager.getInstance().getDatabase()));
        }
        dataList.clear();
        for (Province province : provincesList) {
            emitter.onNext(province.mProName);
        }
        emitter.onComplete();
    }, BackpressureStrategy.BUFFER)
        .compose(RxUtil.ioF())
        .compose(RxUtil.activityLifecycleF(this))
        .doOnNext(proName -> dataList.add(proName))
        .doOnComplete(() -> {
            mProgressBar.setVisibility(View.GONE);
            currentLevel = LEVEL_PROVINCE;
            mAdapter.notifyDataSetChanged();
        })
        .subscribe();
}
 
Example #4
Source File: ChoiceCityActivity.java    From SeeWeather with Apache License 2.0 6 votes vote down vote up
/**
 * 查询选中省份的所有城市,从数据库查询
 */
private void queryCities() {
    getToolbar().setTitle("选择城市");
    dataList.clear();
    mAdapter.notifyDataSetChanged();

    Flowable.create((FlowableOnSubscribe<String>) emitter -> {
        cityList = WeatherDB.loadCities(DBManager.getInstance().getDatabase(), selectedProvince.mProSort);
        for (City city : cityList) {
            emitter.onNext(city.mCityName);
        }
        emitter.onComplete();
    }, BackpressureStrategy.BUFFER)
        .compose(RxUtil.ioF())
        .compose(RxUtil.activityLifecycleF(this))
        .doOnNext(proName -> dataList.add(proName))
        .doOnComplete(() -> {
            currentLevel = LEVEL_CITY;
            mAdapter.notifyDataSetChanged();
            mRecyclerView.smoothScrollToPosition(0);
        })
        .subscribe();
}
 
Example #5
Source File: RxPermissions.java    From RuntimePermission with Apache License 2.0 6 votes vote down vote up
/**
 * use only request with an empty array to request all manifest permissions
 */
public Flowable<PermissionResult> requestAsFlowable(final List<String> permissions) {
    return Flowable.create(new FlowableOnSubscribe<PermissionResult>() {
        @Override
        public void subscribe(final FlowableEmitter<PermissionResult> emitter) throws Exception {
            runtimePermission
                    .request(permissions)
                    .onResponse(new ResponseCallback() {
                        @Override
                        public void onResponse(PermissionResult result) {
                            if (result.isAccepted()) {
                                emitter.onNext(result);
                            } else {
                                emitter.onError(new Error(result));
                            }
                        }
                    }).ask();
        }
    }, BackpressureStrategy.LATEST);
}
 
Example #6
Source File: RxCache.java    From RxCache with Apache License 2.0 6 votes vote down vote up
public <T> Flowable<CacheResult<T>> load2Flowable(final String key, final Type type, BackpressureStrategy backpressureStrategy) {
    return Flowable.create(new FlowableOnSubscribe<CacheResult<T>>() {
        @Override
        public void subscribe(FlowableEmitter<CacheResult<T>> flowableEmitter) throws Exception {
            CacheResult<T> load = cacheCore.load(getMD5MessageDigest(key), type);
            if (!flowableEmitter.isCancelled()) {
                if (load != null) {
                    flowableEmitter.onNext(load);
                    flowableEmitter.onComplete();
                } else {
                    flowableEmitter.onError(new NullPointerException("Not find the key corresponding to the cache"));
                }
            }
        }
    }, backpressureStrategy);
}
 
Example #7
Source File: PhotoPickerDataRepository.java    From CrazyDaily with Apache License 2.0 6 votes vote down vote up
@Override
public Flowable<MediaEntity.MediaResponseData> getMediaList(int imageOffset, int videoOffset, String bucketId) {
    if (TextUtils.isEmpty(bucketId)) {
        return Flowable.empty();
    }
    if (TextUtils.equals(bucketId, String.valueOf(Integer.MAX_VALUE))) {
        // 图片和视频
        return Flowable.create((FlowableOnSubscribe<MediaEntity.MediaResponseData>) e -> {
            e.onNext(handleImageAndVideoMediaList(imageOffset, videoOffset));
            e.onComplete();
        }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io());
    } else if (TextUtils.equals(bucketId, String.valueOf(Integer.MIN_VALUE))) {
        // 所有视频
        return Flowable.create((FlowableOnSubscribe<MediaEntity.MediaResponseData>) e -> {
            e.onNext(handleVideoMediaList(imageOffset, videoOffset));
            e.onComplete();
        }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io());
    } else {
        return Flowable.create((FlowableOnSubscribe<MediaEntity.MediaResponseData>) e -> {
            e.onNext(handleImageMediaList(imageOffset, videoOffset, bucketId));
            e.onComplete();
        }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io());
    }
}
 
Example #8
Source File: ScheduleVideoModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ScheduleVideo> getScheduleVideo(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ScheduleVideo>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ScheduleVideo> e) throws Exception {
      Element html = Jsoup.connect(url).get();
      if(html == null){
        e.onError(new Throwable("element html is null"));
      }else {
        ScheduleVideo scheduleVideo = JP.from(html, ScheduleVideo.class);
        if (!TextUtils.isEmpty(scheduleVideo.getVideoHtml())) {
          scheduleVideo.setVideoUrl("http://tup.yhdm.tv/?m=1&vid=" + scheduleVideo.getVideoUrl());
        }
        /*StringBuilder scheduleVideoHtmlBuilder = new StringBuilder();
        scheduleVideoHtmlBuilder.append(HtmlConstant.SCHEDULE_VIDEO_CSS);
        scheduleVideoHtmlBuilder.append("<div class=\"player_main\" style=\"position: relative;\"> ");
        scheduleVideoHtmlBuilder.append(scheduleVideo.getVideoHtml());
        scheduleVideoHtmlBuilder.append("</div>");
        scheduleVideo.setVideoHtml(scheduleVideoHtmlBuilder.toString());*/
        e.onNext(scheduleVideo);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #9
Source File: ScheduleOtherModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ScheduleOtherPage> getScheduleOtherPage(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ScheduleOtherPage>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ScheduleOtherPage> e) throws Exception {
      Element html = Jsoup.connect(url).get();
      if (html == null) {
        e.onError(new Throwable("element html is null"));
      } else {
        ScheduleOtherPage scheduleOtherPage = JP.from(html, ScheduleOtherPage.class);
        e.onNext(scheduleOtherPage);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #10
Source File: ScheduleNewModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ScheduleNew> getScheduleNew(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ScheduleNew>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ScheduleNew> e) throws Exception {
      Element html = Jsoup.connect(url).get();
      if (html == null) {
        e.onError(new Throwable("element html is null"));
      } else {
        ScheduleNew scheduleNew = JP.from(html, ScheduleNew.class);
        e.onNext(scheduleNew);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #11
Source File: ScheduleDetailModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ScheduleDetail> getScheduleDetail(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ScheduleDetail>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ScheduleDetail> e) throws Exception {
      String scheduleLink = url;
      if (!url.contains("http")) {
        scheduleLink = HtmlConstant.YHDM_M_URL + url;
      }
      Element html = Jsoup.connect(scheduleLink).get();
      if (html == null) {
        e.onError(new Throwable("element html is null"));
      } else {
        ScheduleDetail scheduleDetail = JP.from(html, ScheduleDetail.class);
        e.onNext(scheduleDetail);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #12
Source File: ZeroFiveNewsModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ZeroFiveNewsPage> getAcgNews(final String typeUrl) {
  return Flowable.create(new FlowableOnSubscribe<ZeroFiveNewsPage>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ZeroFiveNewsPage> e) throws Exception {
      Element html = Jsoup.connect(typeUrl).get();
      if(html == null){
        e.onError(new Throwable("element html is null"));
      }else {
        ZeroFiveNewsPage zeroFiveNewsPage = JP.from(html, ZeroFiveNewsPage.class);
        e.onNext(zeroFiveNewsPage);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #13
Source File: ZeroFiveNewsDetailModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ZeroFiveNewsDetail> getAcgNewsDetail(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ZeroFiveNewsDetail>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ZeroFiveNewsDetail> e) throws Exception {
      Element html = Jsoup.connect(url).get();
      if (html == null) {
        e.onError(new Throwable("element html is null"));
      } else {
        ZeroFiveNewsDetail zeroFiveNewsDetail = JP.from(html, ZeroFiveNewsDetail.class);
        e.onNext(zeroFiveNewsDetail);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #14
Source File: AsyncAspect.java    From SAF-AOP with Apache License 2.0 6 votes vote down vote up
private void asyncMethod(final ProceedingJoinPoint joinPoint) throws Throwable {

        Flowable.create(new FlowableOnSubscribe<Object>() {
                            @Override
                            public void subscribe(FlowableEmitter<Object> e) throws Exception {
                                Looper.prepare();
                                try {
                                    joinPoint.proceed();
                                } catch (Throwable throwable) {
                                    throwable.printStackTrace();
                                }
                                Looper.loop();
                            }
                        }
                , BackpressureStrategy.BUFFER)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
    }
 
Example #15
Source File: RxJava2Fetchable.java    From alchemy with Apache License 2.0 6 votes vote down vote up
@Override
public Flowable<T> flowable(BackpressureStrategy mode) {
    return Flowable.create(new FlowableOnSubscribe<T>() {
        @Override
        public void subscribe(FlowableEmitter<T> emitter) throws Exception {
            final CloseableIterator<T> iterator = mCallable.call();
            try {
                while (!emitter.isCancelled() && iterator.hasNext()) {
                    emitter.onNext(iterator.next());
                }
                emitter.onComplete();
            } finally {
                iterator.close();
            }
        }
    }, mode);
}
 
Example #16
Source File: ChapterNine.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo3() {
    Flowable
            .create(new FlowableOnSubscribe<Integer>() {
                @Override
                public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
                    Log.d(TAG, "current requested: " + emitter.requested());
                }
            }, BackpressureStrategy.ERROR)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                    s.request(1000);
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #17
Source File: QQShareInstance.java    From smart-farmer-android with Apache License 2.0 5 votes vote down vote up
@Override
public void shareImage(final int platform, final ShareImageObject shareImageObject,
        final Activity activity, final ShareListener listener) {
    Flowable.create(new FlowableOnSubscribe<String>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<String> emitter) throws Exception {
            try {
                emitter.onNext(ImageDecoder.decode(activity, shareImageObject));
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnRequest(new LongConsumer() {
                @Override
                public void accept(long aLong) {
                    listener.shareRequest();
                }
            })
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String localPath) {
                    if (platform == SharePlatform.QZONE) {
                        shareToQzoneForImage(localPath, activity, listener);
                    } else {
                        shareToQQForImage(localPath, activity, listener);
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    activity.finish();
                    listener.shareFailure(new Exception(throwable));
                }
            });
}
 
Example #18
Source File: ChapterEight.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo2() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
            for (int i = 0; ; i++) {
                emitter.onNext(i);
            }
        }
    }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #19
Source File: ChapterEight.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo1() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
            for (int i = 0; i < 1000; i++) {
                Log.d(TAG, "emit " + i);
                emitter.onNext(i);
            }
        }
    }, BackpressureStrategy.BUFFER).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #20
Source File: ChapterEight.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo7() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
            for (int i = 0; ; i++) {
                Log.d(TAG, "emit " + i);
                emitter.onNext(i);
            }
        }
    }, BackpressureStrategy.MISSING).subscribeOn(Schedulers.io())
            .onBackpressureBuffer()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #21
Source File: ChapterEight.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo3() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
            for (int i = 0; i < 10000; i++) {
                emitter.onNext(i);
            }
        }
    }, BackpressureStrategy.DROP).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                    s.request(128);
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #22
Source File: WxLoginInstance.java    From smart-farmer-android with Apache License 2.0 5 votes vote down vote up
private void getToken(final String code) {
    Flowable.create(new FlowableOnSubscribe<WxToken>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<WxToken> wxTokenEmitter) throws Exception {
            Request request = new Request.Builder().url(buildTokenUrl(code)).build();
            try {
                Response response = mClient.newCall(request).execute();
                JSONObject jsonObject = new JSONObject(response.body().string());
                WxToken token = WxToken.parse(jsonObject);
                wxTokenEmitter.onNext(token);
            } catch (IOException | JSONException e) {
                wxTokenEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<WxToken>() {
                @Override
                public void accept(WxToken wxToken) {
                    if (fetchUserInfo) {
                        mLoginListener.beforeFetchUserInfo(wxToken);
                        fetchUserInfo(wxToken);
                    } else {
                        mLoginListener.loginSuccess(new LoginResult(LoginPlatform.WX, wxToken));
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    mLoginListener.loginFailure(new Exception(throwable.getMessage()));
                }
            });
}
 
Example #23
Source File: ChapterEight.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo4() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
            for (int i = 0; i < 10000; i++) {
                emitter.onNext(i);
            }
        }
    }, BackpressureStrategy.LATEST).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                    s.request(128);
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #24
Source File: WeiboLoginInstance.java    From smart-farmer-android with Apache License 2.0 5 votes vote down vote up
@Override
public void fetchUserInfo(final BaseToken token) {
    Flowable.create(new FlowableOnSubscribe<WeiboUser>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<WeiboUser> weiboUserEmitter) throws Exception {
            OkHttpClient client = new OkHttpClient();
            Request request =
                    new Request.Builder().url(buildUserInfoUrl(token, USER_INFO)).build();
            try {
                Response response = client.newCall(request).execute();
                JSONObject jsonObject = new JSONObject(response.body().string());
                WeiboUser user = WeiboUser.parse(jsonObject);
                weiboUserEmitter.onNext(user);
            } catch (IOException | JSONException e) {
                ShareLogger.e(INFO.FETCH_USER_INOF_ERROR);
                weiboUserEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<WeiboUser>() {
                @Override
                public void accept(WeiboUser weiboUser) {
                    mLoginListener.loginSuccess(
                            new LoginResult(LoginPlatform.WEIBO, token, weiboUser));
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    mLoginListener.loginFailure(new Exception(throwable));
                }
            });
}
 
Example #25
Source File: QQLoginInstance.java    From smart-farmer-android with Apache License 2.0 5 votes vote down vote up
@Override
public void fetchUserInfo(final BaseToken token) {
    Flowable.create(new FlowableOnSubscribe<QQUser>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<QQUser> qqUserEmitter) throws Exception {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(buildUserInfoUrl(token, URL)).build();

            try {
                Response response = client.newCall(request).execute();
                JSONObject jsonObject = new JSONObject(response.body().string());
                QQUser user = QQUser.parse(token.getOpenid(), jsonObject);
                qqUserEmitter.onNext(user);
            } catch (IOException | JSONException e) {
                ShareLogger.e(INFO.FETCH_USER_INOF_ERROR);
                qqUserEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<QQUser>() {
                @Override
                public void accept(@NonNull QQUser qqUser) throws Exception {
                    mLoginListener.loginSuccess(
                            new LoginResult(LoginPlatform.QQ, token, qqUser));
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    mLoginListener.loginFailure(new Exception(throwable));
                }
            });
}
 
Example #26
Source File: ChapterSeven.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo3() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
            Log.d(TAG, "emit 1");
            emitter.onNext(1);
            Log.d(TAG, "emit 2");
            emitter.onNext(2);
            Log.d(TAG, "emit 3");
            emitter.onNext(3);
            Log.d(TAG, "emit complete");
            emitter.onComplete();
        }
    }, BackpressureStrategy.ERROR).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #27
Source File: GetListOperation.java    From HighLite with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches multiple rows from a database and maps them to objects of type {@link T},
 * non-blocking operation.
 *
 * @param strategy the backpressure strategy used for the {@link Flowable}.
 *                 (see {@link BackpressureStrategy})
 * @return an {@link Flowable<T>} where an object of type {@link T} mapped from a database
 * record is passed as the parameter to
 * {@link io.reactivex.observers.DisposableObserver#onNext(Object)}
 */
@Override
public Flowable<T> asFlowable(BackpressureStrategy strategy) {
    return Flowable.create(new FlowableOnSubscribe<T>() {
        @Override
        public void subscribe(FlowableEmitter<T> e) {
            final List<T> items = executeBlocking();
            for (final T item : items) {
                e.onNext(item);
            }
            e.onComplete();
        }
    }, strategy);
}
 
Example #28
Source File: ProducerEvent.java    From SweetMusicPlayer with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the wrapped producer method and produce a {@link Observable}.
 */
public Flowable produce() {
    return Flowable.create(new FlowableOnSubscribe() {
        @Override
        public void subscribe(FlowableEmitter emitter) throws Exception {
            try {
                emitter.onNext(produceEvent());
                emitter.onComplete();
            } catch (InvocationTargetException e) {
                throwRuntimeException("Producer " + ProducerEvent.this + " threw an exception.", e);
            }
        }
    }, BackpressureStrategy.BUFFER).subscribeOn(EventThread.getScheduler(thread));
}
 
Example #29
Source File: FlowableRxInvokerImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private <T> Flowable<T> create(Supplier<T> supplier) {
    Flowable<T> flowable = Flowable.create(new FlowableOnSubscribe<T>() {
        @Override
        public void subscribe(FlowableEmitter<T> emitter) throws Exception {
            try {
                T response = supplier.get();
                if (!emitter.isCancelled()) {
                    emitter.onNext(response);
                }
                
                if (!emitter.isCancelled()) {
                    emitter.onComplete();
                }
            } catch (Throwable e) {
                if (!emitter.isCancelled()) {
                    emitter.onError(e);
                }
            }
        }
    }, BackpressureStrategy.DROP);
    
    if (sc == null) {
        return flowable.subscribeOn(Schedulers.io());
    }
    
    return flowable.subscribeOn(sc).observeOn(sc);
}
 
Example #30
Source File: AbstractEmissionCheckerTest.java    From storio with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void verifySubscribeBehavior() {
    final AtomicBoolean onSubscribeWasCalled = new AtomicBoolean(false);

    final Flowable<String> flowable = Flowable.create(new FlowableOnSubscribe<String>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<String> emitter) throws Exception {
            onSubscribeWasCalled.set(true);
            emitter.onNext("test_value");
            emitter.onComplete();
        }
    }, BackpressureStrategy.MISSING);

    AbstractEmissionChecker<String> emissionChecker = new AbstractEmissionChecker<String>(new LinkedList<String>()) {
        @NonNull
        @Override
        public Disposable subscribe() {
            return flowable.subscribe();
        }
    };

    // Should not subscribe before manual call to subscribe
    assertThat(onSubscribeWasCalled.get()).isFalse();

    Disposable disposable = emissionChecker.subscribe();

    // Should subscribe to flowable
    assertThat(onSubscribeWasCalled.get()).isTrue();

    disposable.dispose();
}