io.reactivex.BackpressureStrategy Java Examples

The following examples show how to use io.reactivex.BackpressureStrategy. 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: DemoFlowable.java    From Reactive-Programming-With-Java-9 with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Flowable<String> month_maybe = Flowable.create(emitter -> {
		try {
			String[] monthArray = { "Jan", "Feb", "Mar", "Apl", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov",
					"Dec" };

			List<String> months = Arrays.asList(monthArray);
			for (String month : months) {
				emitter.onNext(month);
			}
			emitter.onComplete();

		} catch (Exception e) {
			emitter.onError(e);
		}
	},BackpressureStrategy.MISSING);
	month_maybe.subscribe(s -> System.out.println(s));

}
 
Example #2
Source File: UniFromPublisherTest.java    From smallrye-mutiny with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatSubscriberCanCancelBeforeEmission() {
    UniAssertSubscriber<Integer> ts = UniAssertSubscriber.create();
    Uni<Integer> uni = Uni.createFrom().publisher(Flowable.<Integer> create(emitter -> new Thread(() -> {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        emitter.onNext(1);
    }).start(), BackpressureStrategy.DROP)).map(i -> i + 1);

    uni.subscribe().withSubscriber(ts);
    ts.cancel();

    ts.assertNotCompleted();
}
 
Example #3
Source File: AdamantBalanceUpdateService.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
private void startListenBalance(final PublishSubject<Object> subject){
    Disposable subscribe =
            api
                .updateBalance()
                .repeatWhen((completed) -> completed.delay(
                        BuildConfig.UPDATE_BALANCE_SECONDS_DELAY,
                        TimeUnit.SECONDS
                ))
                .retryWhen((completed) -> completed.delay(
                        BuildConfig.UPDATE_BALANCE_SECONDS_DELAY,
                        TimeUnit.SECONDS
                ))
                .repeatWhen(repeatHandler ->
                        repeatHandler.flatMap(nothing -> subject.toFlowable(BackpressureStrategy.LATEST)))
                .subscribe();

    compositeDisposable.add(subscribe);
}
 
Example #4
Source File: PoAManager.java    From asf-sdk with GNU General Public License v3.0 6 votes vote down vote up
private void handleCampaign() {
  compositeDisposable.add(ReactiveNetwork.observeInternetConnectivity()
      .subscribeOn(Schedulers.io())
      .filter(hasInternet -> hasInternet)
      .filter(__ -> this.campaignId == null)
      .firstOrError()
      .flatMap(__ -> campaignService.getCampaign())
      .retryWhen(throwableObservable -> throwableObservable.toObservable()
          .flatMap(throwable -> {
            throwable.printStackTrace();
            return ReactiveNetwork.observeInternetConnectivity();
          })
          .flatMap(this::retryIfNetworkAvailable)
          .toFlowable(BackpressureStrategy.LATEST))
      .doOnSuccess(this::processCampaign)
      .subscribe());
}
 
Example #5
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 #6
Source File: SimpleNetBoundResource.java    From RetrofitGO with Apache License 2.0 6 votes vote down vote up
public SimpleNetBoundResource() {
    flowable = Flowable.create(emitter -> {
        // 加载中
        emitter.onNext(Resource.loading(null));
        // 从网络加载数据
        fetchFromNet().subscribe(
                response -> { // 成功
                    saveResult(response);
                    emitter.onNext(Resource.success(response));
                },
                e -> {  // 失败
                    RxHelper.handleError(e).subscribe(error -> {
                        emitter.onNext(Resource.<T>error(error.getCode(), error.getMessage(), null));
                    });
                });
    }, BackpressureStrategy.BUFFER);
}
 
Example #7
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 #8
Source File: RxReporter.java    From buffer-slayer with Apache License 2.0 6 votes vote down vote up
private RxReporter(Builder<M, R> builder) {
  this.sender = builder.sender;
  this.metrics = builder.metrics;

  this.messageTimeoutNanos = builder.messageTimeoutNanos;
  this.bufferedMaxMessages = builder.bufferedMaxMessages;
  this.pendingMaxMessages = builder.pendingMaxMessages;
  this.overflowStrategy = builder.overflowStrategy;
  this.scheduler = builder.scheduler;

  Flowable<MessagePromise<R>> flowable = Flowable.create(this, BackpressureStrategy.MISSING);
  initBackpressurePolicy(flowable)
      .observeOn(Schedulers.single())
      .groupBy(new MessagePartitioner())
      .subscribe(new MessageGroupSubscriber(messageTimeoutNanos, bufferedMaxMessages, sender, scheduler));
}
 
Example #9
Source File: Subscription.java    From dive-into-graphql-in-java with GNU General Public License v3.0 6 votes vote down vote up
public Publisher<Score> talkScores(final String title) {
    Observable<Score> observable = Observable.create(e -> {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleAtFixedRate(() -> {
            Score s = Score.builder()
                           .title(title)
                           .score(Integer.valueOf((int) Math.floor(Math.random()*10)))
                           .build();
            e.onNext(s);
        }, 0, 2, TimeUnit.SECONDS);
    });

    ConnectableObservable connectableObservable = observable.share().publish();
    connectableObservable.connect();
    return connectableObservable.toFlowable(BackpressureStrategy.BUFFER);
}
 
Example #10
Source File: RestHelper.java    From mvvm-template with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a mapper from retrofit service to {@link Resource} with rx's {@link Flowable}
 * To indicate current state while execute an rest api (loading, error, success with status and message if error)
 * @param remote from retrofit service
 * @param onSave will be called after success response come, to save response data into local database
 * @param <T> type of response
 * @return a {@link Flowable} instance to deal with progress showing and error handling
 */
public static <T> Flowable<Resource<T>> createRemoteSourceMapper(@Nullable Single<T> remote,
                                                                 @Nullable PlainConsumer<T> onSave) {
    return Flowable.create(emitter -> {
        new SimpleRemoteSourceMapper<T>(emitter) {

            @Override
            public Single<T> getRemote() {
                return remote;
            }

            @Override
            public void saveCallResult(T data) {
                if (onSave != null) {
                    onSave.accept(data);
                }
            }
        };
    }, BackpressureStrategy.BUFFER);
}
 
Example #11
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 #12
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 #13
Source File: RxPaperBookTest.java    From RxPaper2 with MIT License 6 votes vote down vote up
@Test
public void testUpdatesAllChecked() throws Exception {
    RxPaperBook book = RxPaperBook.with("UPDATES_ALL_CH", Schedulers.trampoline());
    final String key = "hello";
    final ComplexObject value = ComplexObject.random();
    final TestSubscriber<ComplexObject> updatesSubscriber = TestSubscriber.create();
    book.observeAll(ComplexObject.class, BackpressureStrategy.MISSING).subscribe(updatesSubscriber);
    updatesSubscriber.assertValueCount(0);
    book.write(key, value).subscribe();
    updatesSubscriber.assertValueCount(1);
    updatesSubscriber.assertValues(value);
    final ComplexObject newValue = ComplexObject.random();
    book.write(key, newValue).subscribe();
    updatesSubscriber.assertValueCount(2);
    updatesSubscriber.assertValues(value, newValue);
    // Error value
    final int wrongValue = 3;
    book.write(key, wrongValue).test().assertComplete().assertNoErrors();
    updatesSubscriber.assertValueCount(2);
    updatesSubscriber.assertValues(value, newValue);
    updatesSubscriber.assertNoErrors();
}
 
Example #14
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 #15
Source File: GitHubServiceImpl.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable<Commit> getCommitsInWeek(String user, String repo) {
    return Flowable.create(emitter -> {
        gitHbubRepos.getCommitsInWeek(user, repo)
                    .forEach(emitter::onNext);
        emitter.onComplete();
    }, BackpressureStrategy.BUFFER);
}
 
Example #16
Source File: RxJavaFragment.java    From AndroidQuick with MIT License 5 votes vote down vote up
/**
 * 注意:只有在有背压需求的时候才需要使用Flowable, 否则使用Observable, 不然会影响性能
 */
private void testFlowable() {//flowable比observable多了一个缓冲池大小的限制
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> e) throws Exception {
            System.out.println("send----> 1");
            e.onNext(1);
            System.out.println("send----> 2");
            e.onNext(2);
            System.out.println("send----> 3");
            e.onNext(3);
            System.out.println("send----> Done");
            e.onComplete();
        }
    }, BackpressureStrategy.BUFFER) //add param: BackpressureStrategy
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {
                @Override
                public void onSubscribe(Subscription s) {
                    s.request(Long.MAX_VALUE);
                }

                @Override
                public void onNext(Integer integer) {
                    System.out.println("receive----> " + integer);
                    mFlowableResult.setText("receive----> " + integer);
                }

                @Override
                public void onError(Throwable t) {
                }

                @Override
                public void onComplete() {
                    System.out.println("receive----> Done");
                    mFlowableResult.setText("receive----> Done");
                }
            });
}
 
Example #17
Source File: GitHubServiceImpl.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable<String> getReposInWeek(String user) {
    return Flowable.create(emitter -> {
        gitHbubRepos.getRepos(user).stream()
                    .filter(repo -> repo.getPushed().isAfter(LocalDateTime.now().minusWeeks(1)))
                    .map(item -> item.getName() + " ")
                    .forEach(emitter::onNext);
        emitter.onComplete();
    }, BackpressureStrategy.BUFFER);
}
 
Example #18
Source File: RxBus.java    From KotlinMVPRxJava2Dagger2GreenDaoRetrofitDemo with Apache License 2.0 5 votes vote down vote up
private RxBus() {
    flowable = Flowable.create(new FlowableOnSubscribe<T>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<T> e) throws Exception {
            emmiter = e;
        }
    }, BackpressureStrategy.ERROR);
}
 
Example #19
Source File: GitHubServiceImpl.java    From Java-9-Spring-Webflux with Apache License 2.0 5 votes vote down vote up
@Override
public Flowable<CommittedFile> getCommittedFiles(String user, String repo, String sha) {
    return Flowable.create(emitter -> {
        gitHbubRepos.getSingleCommit(user, repo, sha).getFiles()
                    .forEach(emitter::onNext);
        emitter.onComplete();
    }, BackpressureStrategy.BUFFER);
}
 
Example #20
Source File: RxQuery.java    From ObjectBoxRxJava with Apache License 2.0 5 votes vote down vote up
/**
 * The returned Flowable emits Query results one by one. Once all results have been processed, onComplete is called.
 * Uses given BackpressureStrategy.
 */
public static <T> Flowable<T> flowableOneByOne(final Query<T> query, BackpressureStrategy strategy) {
    return Flowable.create(new FlowableOnSubscribe<T>() {
        @Override
        public void subscribe(final FlowableEmitter<T> emitter) throws Exception {
            createListItemEmitter(query, emitter);
        }

    }, strategy);
}
 
Example #21
Source File: FlowableToRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
protected Optional<Flowable> createInstanceEmittingAMultipleValuesAndFailure(String v1, String v2,
        RuntimeException e) {
    Flowable<String> stream = Flowable.create(emitter -> {
        emitter.onNext(v1);
        emitter.onNext(v2);
        emitter.onError(e);
    }, BackpressureStrategy.ERROR);
    return Optional.of(stream);
}
 
Example #22
Source File: LocationManager.java    From ground-android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the location update stream. New subscribers and downstream subscribers that can't keep
 * up will only see the latest location.
 */
public Flowable<Point> getLocationUpdates() {
  // There sometimes noticeable latency between when location update request succeeds and when
  // the first location update is received. Requesting the last know location is usually
  // immediate, so we merge into the stream to reduce perceived latency.
  return getLastLocation()
      .toObservable()
      .mergeWith(locationUpdates.map(LocationManager::toPoint))
      .toFlowable(BackpressureStrategy.LATEST);
}
 
Example #23
Source File: FlowableToCompletionStageTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
protected Optional<Flowable> createInstanceEmittingAMultipleValuesAndFailure(String v1, String v2,
        RuntimeException e) {
    Flowable<String> stream = Flowable.create(emitter -> {
        emitter.onNext(v1);
        emitter.onNext(v2);
        emitter.onError(e);
    }, BackpressureStrategy.ERROR);
    return Optional.of(stream);
}
 
Example #24
Source File: RxJavaUtils.java    From Collection-Android with MIT License 5 votes vote down vote up
/**
 * 执行Rx通用任务 (IO线程中执行耗时操作 执行完成调用UI线程中的方法)
 *
 * @param rxTask        执行任务
 * @param errorConsumer 出错的处理
 * @param <T>
 * @return
 */
public static <T, R> Disposable executeAsyncTask(@NonNull RxAsyncTask<T, R> rxTask, @NonNull Consumer<Throwable> errorConsumer) {
    RxTaskOnSubscribe<RxAsyncTask<T, R>> onSubscribe = getRxAsyncTaskOnSubscribe(rxTask);
    return Flowable.create(onSubscribe, BackpressureStrategy.LATEST)
            .compose(RxSchedulerUtils.<RxAsyncTask<T, R>>_io_main_f())
            .subscribe(new Consumer<RxAsyncTask<T, R>>() {
                @Override
                public void accept(RxAsyncTask<T, R> rxAsyncTask) throws Exception {
                    rxAsyncTask.doInUIThread(rxAsyncTask.getOutData());  //在UI线程工作
                }
            }, errorConsumer);
}
 
Example #25
Source File: InsLoginInstance.java    From ShareLoginPayUtil with Apache License 2.0 5 votes vote down vote up
@Override
public void fetchUserInfo(final BaseToken token) {
    mSubscribe = Flowable.create(new FlowableOnSubscribe<InsUser>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<InsUser> insUserEmitter) {

            Request post = new Request.Builder().url(sTokenUrl).post(buildUserInfoUrl(token)).build();
            try {
                Response response = mClient.newCall(post).execute();
                JSONObject jsonObject = new JSONObject(response.body().string());
                ShareLogger.i("auth:" + jsonObject.toString());
                InsUser user = new InsUser(jsonObject);
                insUserEmitter.onNext(user);
                insUserEmitter.onComplete();
            } catch (IOException | JSONException e) {
                insUserEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<InsUser>() {
                @Override
                public void accept(@NonNull InsUser insUser) {
                    mLoginListener.loginSuccess(new LoginResultData(LoginPlatform.INS, token, insUser));
                    LoginUtil.recycle();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) {
                    mLoginListener.loginFailure(new Exception(throwable), ShareLogger.INFO.ERR_FETCH_CODE);
                    LoginUtil.recycle();
                }
            });
}
 
Example #26
Source File: WxLoginInstance.java    From ShareLoginPayUtil with Apache License 2.0 5 votes vote down vote up
@SuppressLint("CheckResult")
private void getToken(final String code) {
    mTokenSubscribe = Flowable.create(new FlowableOnSubscribe<WxToken>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<WxToken> wxTokenEmitter) {
            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 = new WxToken(jsonObject);
                wxTokenEmitter.onNext(token);
                wxTokenEmitter.onComplete();
            } catch (IOException | JSONException e) {
                wxTokenEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<WxToken>() {
                @Override
                public void accept(@NonNull WxToken wxToken) {
                    if (mFetchUserInfo) {
                        mLoginListener.beforeFetchUserInfo(wxToken);
                        fetchUserInfo(wxToken);
                    } else {
                        mLoginListener.loginSuccess(new LoginResultData(LoginPlatform.WX, wxToken));
                        LoginUtil.recycle();
                    }

                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) {
                    mLoginListener.loginFailure(new Exception(throwable.getMessage()), ShareLogger.INFO.ERR_GET_TOKEN_CODE);
                    LoginUtil.recycle();
                }
            });
}
 
Example #27
Source File: TwitterLoginInstance.java    From ShareLoginPayUtil with Apache License 2.0 5 votes vote down vote up
@SuppressLint("CheckResult")
@Override
public void fetchUserInfo(final BaseToken token) {
    mSubscribe = Flowable.create(new FlowableOnSubscribe<TwitterUser>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<TwitterUser> userEmitter) {

            TwitterApiClient apiClient = TwitterCore.getInstance().getApiClient();
            Call<User> userCall = apiClient.getAccountService().verifyCredentials(true, false, false);

            try {
                Response<User> execute = userCall.execute();
                userEmitter.onNext(new TwitterUser(execute.body()));
                userEmitter.onComplete();
            } catch (Exception e) {
                ShareLogger.e(ShareLogger.INFO.FETCH_USER_INOF_ERROR);
                userEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<TwitterUser>() {
                @Override
                public void accept(@NonNull TwitterUser user) {
                    mLoginListener.loginSuccess(new LoginResultData(LoginPlatform.TWITTER, token, user));
                    LoginUtil.recycle();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) {
                    mLoginListener.loginFailure(new Exception(throwable), ShareLogger.INFO.ERR_FETCH_CODE);
                    LoginUtil.recycle();
                }
            });
}
 
Example #28
Source File: WeiboLoginInstance.java    From ShareLoginPayUtil with Apache License 2.0 5 votes vote down vote up
@SuppressLint("CheckResult")
@Override
public void fetchUserInfo(final BaseToken token) {
    mSubscribe = Flowable.create(new FlowableOnSubscribe<WeiboUser>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<WeiboUser> weiboUserEmitter) {
            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);
                weiboUserEmitter.onComplete();
            } catch (IOException | JSONException e) {
                ShareLogger.e(ShareLogger.INFO.FETCH_USER_INOF_ERROR);
                weiboUserEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<WeiboUser>() {
                @Override
                public void accept(@NonNull WeiboUser weiboUser) throws Exception {
                    mLoginListener.loginSuccess(
                            new LoginResultData(LoginPlatform.WEIBO, token, weiboUser));
                    LoginUtil.recycle();
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) throws Exception {
                    mLoginListener.loginFailure(new Exception(throwable), ShareLogger.INFO.ERR_FETCH_CODE);
                    LoginUtil.recycle();
                }
            });
}
 
Example #29
Source File: QQShareInstance.java    From ShareLoginPayUtil with Apache License 2.0 5 votes vote down vote up
@SuppressLint("CheckResult")
@Override
public void shareImage(final int platform, final ShareImageObject shareImageObject,
                       final Activity activity, final ShareListener listener) {
    mShareImage = 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())
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(@NonNull String localPath) throws Exception {
                    if (platform == SharePlatform.QZONE) {
                        shareToQzoneForImage(localPath, activity, listener);
                    } else {
                        shareToQQForImage(localPath, activity, listener);
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) throws Exception {
                    listener.shareFailure(new Exception(throwable));
                    recycle();
                    activity.finish();
                }
            });
}
 
Example #30
Source File: WeiboShareInstance.java    From ShareLoginPayUtil with Apache License 2.0 5 votes vote down vote up
@SuppressLint("CheckResult")
private void shareTextOrImage(final Pair<String, byte[]> shareImageObject, final String title, final String targetUrl, final String summary,
                              final Activity activity, final ShareListener listener) {

    mShareImage = Flowable.create(new FlowableOnSubscribe<Pair<String, byte[]>>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<Pair<String, byte[]>> emitter) {
            try {
                emitter.onNext(shareImageObject);
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Pair<String, byte[]>>() {
                @Override
                public void accept(@NonNull Pair<String, byte[]> stringPair) {
                    handleShare(stringPair, title, targetUrl, summary, listener);
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(@NonNull Throwable throwable) {
                    listener.shareFailure(new Exception(throwable));
                    recycle();
                    activity.finish();
                }
            });
}