Java Code Examples for io.reactivex.disposables.Disposable

The following are top voted examples for showing how to use io.reactivex.disposables.Disposable. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AmenEye   File: AboutMePresenter.java   Source Code and License 7 votes vote down vote up
public void loadInfo(String user) {
    ApiManager.getInstence().getGithubService()
            .getMyInfo(user).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<UserInfo>() {
                @Override
                public void onSubscribe(Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onNext(UserInfo value) {
                    mIAboutMeActivity.showMyInfo(value);
                }

                @Override
                public void onError(Throwable e) {
                    mIAboutMeActivity.loadMyInfoFail();
                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example 2
Project: RxLifecycle   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void disposeOnResume() {
    Disposable d = Observable
            .interval(1, TimeUnit.SECONDS)
            .subscribeWith(new DisposableObserver<Long>() {
                @Override
                public void onNext(Long value) {
                    Log.d(TAG, "Timer A:" + value.toString() + " Seconds");
                }

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

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });

    /*
     * Dispose observer on ActivityEvent.RESUME
     */
    dispose(d, ActivityEvent.RESUME);
}
 
Example 3
Project: chaosflix   File: ConferencesBrowseFragment.java   Source Code and License 6 votes vote down vote up
private Disposable updateWatchlist(List<WatchlistItem> watchlistItems) {
		return ((LeanbackBaseActivity) getActivity()).getApiServiceObservable()
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(mediaApiService -> {
					showWatchlist();
					watchListAdapter.clear();
					if(watchlistItems.size() > 0){
//						int i = Math.max(0,mRowsAdapter.indexOf(mConferencesSection));
//						mRowsAdapter.add(i,mRecomendationsSectionsRow);
//						mRowsAdapter.add(i+1,watchListAdapter);
						Observable.fromIterable(watchlistItems)
								.flatMap(watchlistItem -> mediaApiService.getEvent(watchlistItem.getEventId()))
								.observeOn(AndroidSchedulers.mainThread())
								.subscribe(event -> watchListAdapter.add(event));
					} else {
//						watchListAdapter.add("Watchlist empty");
						hideWatchlist();
					}
				});
	}
 
Example 4
Project: grpc-mate   File: RxStreamObserverTest.java   Source Code and License 6 votes vote down vote up
@Test
public void clientStreaming_error_break_flow() throws Exception {
  PublishSubject<Integer> publishSubject = PublishSubject.create();
  Set<Integer> resultsHolder = Sets.newConcurrentHashSet();
  Set<Throwable> exceptionsHolder = Sets.newConcurrentHashSet();
  AtomicBoolean complete = new AtomicBoolean(false);
  Disposable disposable = publishSubject
      .doOnNext(num->resultsHolder.add(num))
      .doOnError(t->exceptionsHolder.add(t))
      .doOnComplete(()->complete.compareAndSet(false,true))
      .subscribe();
  assertThat(disposable.isDisposed()).isFalse();
  RxStreamObserver<Integer> rxStreamObserver = new RxStreamObserver<>(publishSubject);

  rxStreamObserver.onError(new IllegalStateException());

  assertThat(disposable.isDisposed()).isTrue();
  assertThat(resultsHolder).isEmpty();
  assertThat(exceptionsHolder.size()).isEqualTo(1);
  assertThat(exceptionsHolder.iterator().next()).isInstanceOf(IllegalStateException.class);
  assertThat(complete).isFalse();
}
 
Example 5
Project: android-contact-extractor   File: ContactInfoFragment.java   Source Code and License 6 votes vote down vote up
private Disposable readAndFillContacts(final int filterType) {
    CQuery cQuery = CQuery.getInstance(getActivity());
    cQuery.filter(filterType);
    return cQuery.build(new IContact() {
        @Override
        public void onContactSuccess(List<CList> mList) {
            //Toast.makeText(getActivity(), " Contacts count " + mList.size(), Toast.LENGTH_SHORT).show();
            if (mList != null && !mList.isEmpty()) {
                for (CList cList : mList) {
                    setUpContactList(filterType, cList);
                }

                mList.clear();
            }

            updateList();
        }

        @Override
        public void onContactError(Throwable throwable) {
            Toast.makeText(getActivity(), "" + throwable.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }
    });

}
 
Example 6
Project: Demos   File: MainActivity.java   Source Code and License 6 votes vote down vote up
/**
 * Rx方式使用
 */
private void rxRequest() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constant.SERVER_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 支持RxJava
            .client(RetrofitUtils.getOkHttpClient()) // 打印请求参数
            .build();

    RetrofitService service = retrofit.create(RetrofitService.class);
    Observable<PostInfo> observable = service.getPostInfoRx("yuantong", "11111111111");
    observable.subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
            .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
            .subscribe(new Observer<PostInfo>() {  // 订阅
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull PostInfo postInfo) {
                    Log.i("http返回:", postInfo.toString());
                    Toast.makeText(MainActivity.this, postInfo.toString(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example 7
Project: Reactive-Android-Programming   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void demo1() {

        final Disposable subscribe = Observable.create(emitter -> {
            emitter.setCancellable(() -> {
                log("setCancellable");
                helloText.setOnClickListener(null);
            });
            helloText.setOnClickListener(v -> {
                log("listener", "Click");
                emitter.onNext(v);
            });
        })
                .doOnDispose(() -> log("onDispose"))
                .doOnComplete(() -> log("doOnComplete"))
                .subscribe(e -> log("subscribe", "Click"));
        subscribe.dispose();
    }
 
Example 8
Project: RxEasyHttp   File: RxUtil.java   Source Code and License 6 votes vote down vote up
public static <T> ObservableTransformer<T, T> io_main() {
    return new ObservableTransformer<T, T>() {
        @Override
        public ObservableSource<T> apply(@NonNull Observable<T> upstream) {
            return upstream
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            HttpLog.i("+++doOnSubscribe+++" + disposable.isDisposed());
                        }
                    })
                    .doFinally(new Action() {
                        @Override
                        public void run() throws Exception {
                            HttpLog.i("+++doFinally+++");
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread());
        }
    };
}
 
Example 9
Project: ZhaZhaShop   File: MovieMoreRankPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void getOverseaComingMovieList(String area, int limit, int offset) {
    mManager.getOverseaComingMovie(area, limit, offset)
            .subscribe(new Observer<OverseaComingMovieBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    mView.showLoading();
                }

                @Override
                public void onNext(@NonNull OverseaComingMovieBean data) {
                    mView.addOverseaComingMovieList(data.getData().getComing());
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    mView.showError(ErrorHanding.handleError(e));
                }

                @Override
                public void onComplete() {
                    mView.showContent();
                }
            });
}
 
Example 10
Project: Rxjava2.0Demo   File: DoActivity.java   Source Code and License 6 votes vote down vote up
private void processRepeat() {
    Observable.just(1, 2, 3)
            .repeat(3)
            .subscribe(new Observer<Integer>() {
                @Override
                public void onSubscribe(Disposable d) {
                    Log.d(TAG, "开始采用subscribe连接");
                }

                @Override
                public void onNext(Integer value) {
                    Log.d(TAG, "接收到了事件" + value);
                }

                @Override
                public void onError(Throwable e) {
                    Log.d(TAG, "对Error事件作出响应");
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "对Complete事件作出响应");
                }

            });
}
 
Example 11
Project: Aurora   File: VideoDetailPresenter.java   Source Code and License 6 votes vote down vote up
public void getSecondRelaRelateVideoInfo(String path, int id, int startnum) {
    mModel.getSecondRelateVideoInfo(path, id, startnum).compose(RxUtils.applySchedulersWithLifeCycle(mRootView))
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(@NonNull Disposable disposable) throws Exception {
                    if (startnum==0){
                        mRootView.showLoading();
                    }
                }
            })
            .subscribe(new ErrorHandleSubscriber<VideoListInfo>(mErrorHandler) {
                @Override
                public void onNext(VideoListInfo info) {
                    mRootView.setData(info, true);
                }
            });
}
 
Example 12
Project: RxLifecycle   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private void disposeOnDestroy() {
    Disposable d = Observable
            .interval(1, TimeUnit.SECONDS)
            .subscribeWith(new DisposableObserver<Long>() {
                @Override
                public void onNext(Long value) {
                    Log.d(TAG, "Timer B:" + value.toString() + " Seconds");
                }

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

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });

    /*
     * Dispose observer
     */
    dispose(d);
}
 
Example 13
Project: Rxjava2.0Demo   File: CreateActivity.java   Source Code and License 6 votes vote down vote up
private void from() {
    String[] items = new String[]{"1", "2", "3"};
    final Disposable[] mDisposable = new Disposable[1];
    Observable.fromArray(items)
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(Disposable disposable) throws Exception {
                    mDisposable[0] = disposable;
                }
            }).subscribe(new Consumer<String>() {
        @Override
        public void accept(String s) throws Exception {
            if (s.equals("2")) {
                mDisposable[0].dispose();
            }
            Log.e(TAG, "accept: " + s);
        }
    });

}
 
Example 14
Project: NeiHanDuanZiTV   File: RxUtils.java   Source Code and License 6 votes vote down vote up
public static <T> ObservableTransformer<T, T> applySchedulers(final IView view) {
    return new ObservableTransformer<T, T>() {
        @Override
        public Observable<T> apply(Observable<T> observable) {
            return observable.subscribeOn(Schedulers.io())
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            view.showLoading();//显示进度条
                        }
                    })
                    .subscribeOn(AndroidSchedulers.mainThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doAfterTerminate(new Action() {
                        @Override
                        public void run() {
                            view.hideLoading();//隐藏进度条
                        }
                    }).compose(RxUtils.bindToLifecycle(view));
        }
    };
}
 
Example 15
Project: GitHub   File: HandlerSchedulerTest.java   Source Code and License 6 votes vote down vote up
@Test @Ignore("Implementation delegated to default RxJava implementation")
public void directSchedulePeriodicallyDisposedDoesNotRun() {
    CountingRunnable counter = new CountingRunnable();
    Disposable disposable = scheduler.schedulePeriodicallyDirect(counter, 1, 1, MINUTES);

    runUiThreadTasks();
    assertEquals(0, counter.get());

    idleMainLooper(1, MINUTES);
    runUiThreadTasks();
    assertEquals(1, counter.get());

    idleMainLooper(1, MINUTES);
    runUiThreadTasks();
    assertEquals(2, counter.get());

    disposable.dispose();

    idleMainLooper(1, MINUTES);
    runUiThreadTasks();
    assertEquals(2, counter.get());
}
 
Example 16
Project: GitHub   File: HandlerSchedulerTest.java   Source Code and License 6 votes vote down vote up
@Test @Ignore("Implementation delegated to default RxJava implementation")
public void workerSchedulePeriodicallyDisposedDoesNotRun() {
    Worker worker = scheduler.createWorker();

    CountingRunnable counter = new CountingRunnable();
    Disposable disposable = worker.schedulePeriodically(counter, 1, 1, MINUTES);

    runUiThreadTasks();
    assertEquals(0, counter.get());

    idleMainLooper(1, MINUTES);
    runUiThreadTasks();
    assertEquals(1, counter.get());

    idleMainLooper(1, MINUTES);
    runUiThreadTasks();
    assertEquals(2, counter.get());

    disposable.dispose();

    idleMainLooper(1, MINUTES);
    runUiThreadTasks();
    assertEquals(2, counter.get());
}
 
Example 17
Project: Rxjava2.0Demo   File: SplashActivity.java   Source Code and License 6 votes vote down vote up
private void start() {
    Disposable disposable = Observable.interval(1, TimeUnit.SECONDS)
            .take(1)
            .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends Long>>() {
                @Override
                public ObservableSource<? extends Long> apply(Throwable throwable) throws Exception {
                    return null;
                }
            })
            .subscribe(new Consumer<Long>() {
                @Override
                public void accept(Long aLong) throws Exception {
                    Log.e(MainActivity.TAG, "accept: " + aLong);
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }
            });
    dLists.add(disposable);

}
 
Example 18
Project: NovelReader   File: CommentDetailPresenter.java   Source Code and License 6 votes vote down vote up
@Override
public void loadComment(String detailId, int start, int limit) {
    Disposable loadDispo = RemoteRepository.getInstance()
            .getDetailComments(detailId, start, limit)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    (bean) -> {
                        mView.finishLoad(bean);
                    },
                    (e) -> {
                        mView.showLoadError();
                        LogUtils.e(e);
                    }
            );
    addDisposable(loadDispo);
}
 
Example 19
Project: vertx-kubernetes-workshop   File: Helpers.java   Source Code and License 5 votes vote down vote up
/**
 * Utility method to report the completion/failure from a Single to a Future.
 *
 * @param future the future
 * @return the single observer to pass to {@link Single#subscribe()}
 */
public static SingleObserver<JsonObject> toObserver(Future<JsonObject> future) {
    return new SingleObserver<JsonObject>() {
        public void onSubscribe(@NonNull Disposable d) {
        }

        public void onSuccess(@NonNull JsonObject item) {
            future.tryComplete(item);
        }

        public void onError(Throwable error) {
            future.tryFail(error);
        }
    };
}
 
Example 20
Project: Learning-RxJava   File: Ch6_20.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Disposable d = Observable.interval(1, TimeUnit.SECONDS)
            .doOnDispose(() -> System.out.println("Disposing on thread"
                            + Thread.currentThread().getName()))
            .unsubscribeOn(Schedulers.io())
            .subscribe(i -> System.out.println("Received " +
                    i));
    sleep(3000);
    d.dispose();
    sleep(3000);
}
 
Example 21
Project: ConductorMVP   File: TideDetailsController.java   Source Code and License 5 votes vote down vote up
@Override protected void attachView(final TideDetailsView view) {
  super.attachView(view);
  DemoApplication.app(getApplicationContext()).injector().inject(this);
  view.setTitle(tideLocationName);
  noaaApi.getTideInfo(noaaApiId)
      .observeOn(AndroidSchedulers.mainThread())
      .compose(this.<TideInfo>bindToLifecycle())
      .subscribe(new Observer<TideInfo>() {
        @Override public void onSubscribe(@NonNull Disposable d) {

        }

        @Override public void onNext(@NonNull TideInfo tideInfo) {
          if (tideInfo.getData() != null && !tideInfo.getData().isEmpty()) {
            List<Observation> observations = tideInfo.getData();
            BigDecimal highestMeasuredTideHeight =
                Collections.max(filterOutNullMeasurements(observations), OBSERVATION_COMPARATOR)
                    .getVerifiedWaterLevel();
            BigDecimal lowestMeasuredTideHeight =
                Collections.min(filterOutNullMeasurements(observations), OBSERVATION_COMPARATOR)
                    .getVerifiedWaterLevel();
            BigDecimal latestMeasuredTideHeight =
                observations.get(observations.size() - 1).getVerifiedWaterLevel();
            view.setTideHeights(latestMeasuredTideHeight, lowestMeasuredTideHeight,
                highestMeasuredTideHeight);
          }
        }

        @Override public void onError(@NonNull Throwable e) {
          view.showError();
        }

        @Override public void onComplete() {

        }
      });
}
 
Example 22
Project: Learning-RxJava   File: Ch2_33.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
        Observable<Long> seconds =
                Observable.interval(1, TimeUnit.SECONDS);
        Disposable disposable =
                seconds.subscribe(l -> System.out.println("Received: " + l));
//sleep 5 seconds
        sleep(5000);
//dispose and stop emissions
        disposable.dispose();
//sleep 5 seconds to prove
//there are no more emissions
        sleep(5000);
    }
 
Example 23
Project: RxJava2-Android-Sample   File: SkipExampleActivity.java   Source Code and License 5 votes vote down vote up
private Observer<Integer> getObserver() {
    return new Observer<Integer>() {

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

        @Override
        public void onNext(Integer value) {
            textView.append(" onNext : value : " + value);
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onNext value : " + value);
        }

        @Override
        public void onError(Throwable e) {
            textView.append(" onError : " + e.getMessage());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onError : " + e.getMessage());
        }

        @Override
        public void onComplete() {
            textView.append(" onComplete");
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onComplete");
        }
    };
}
 
Example 24
Project: NovelReader   File: BookDetailPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void addToBookShelf(CollBookBean collBookBean)  {
    Disposable disposable = RemoteRepository.getInstance()
            .getBookChapters(collBookBean.get_id())
            .subscribeOn(Schedulers.io())
            .doOnSubscribe(
                    (d) -> mView.waitToBookShelf() //等待加载
            )
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    beans -> {

                        //设置 id
                        for(BookChapterBean bean :beans){
                            bean.setId(MD5Utils.strToMd5By16(bean.getLink()));
                        }

                        //设置目录
                        collBookBean.setBookChapters(beans);
                        //存储收藏
                        BookRepository.getInstance()
                                .saveCollBookWithAsync(collBookBean);

                        mView.succeedToBookShelf();
                    }
                    ,
                    e -> {
                        mView.errorToBookShelf();
                        LogUtils.e(e);
                    }
            );
    addDisposable(disposable);
}
 
Example 25
Project: GifEmoji   File: EmoticonDrawable.java   Source Code and License 5 votes vote down vote up
void animation() {
    if (delay > 0 && frameNum > 0)
        Observable
                .interval(delay, TimeUnit.MILLISECONDS)
                .flatMap(new Function<Long, ObservableSource<Long>>() {
                    @Override
                    public ObservableSource<Long> apply(Long aLong) throws Exception {
                        return Observable.just(aLong);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long drawable) {
                        position++;
                        if (position >= frameNum) position = 0;
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
}
 
Example 26
Project: RxJava2-Android-Sample   File: TimestampExampleActivity.java   Source Code and License 5 votes vote down vote up
private Observer<Timed<String>> getObserver() {
    return new Observer<Timed<String>>() {

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

        @Override
        public void onNext(Timed<String> value) {
            textView.append(" onNext : value : " + value.value() + ", time:" + value.time());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onNext : value : " + value);
        }

        @Override
        public void onError(Throwable e) {
            textView.append(" onError : " + e.getMessage());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onError : " + e.getMessage());
        }

        @Override
        public void onComplete() {
            textView.append(" onComplete");
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onComplete");
        }
    };
}
 
Example 27
Project: MovingGdufe-Android   File: MeFragment.java   Source Code and License 5 votes vote down vote up
private void queryCurrentCash(){
    cardFactory.getCurrentCash(new Observer<CardBasic>() {
        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onNext(CardBasic value) {
            if(null != value && !TextUtils.isEmpty(value.getCash())) {
                tvMeCash.setText("¥" + value.getCash());
                mCardNum = value.getCardNum();
            }else{
                tvMeCash.setText("获取失败");
            }
        }
        @Override
        public void onError(Throwable e) {
            if(e != null && !TextUtils.isEmpty(e.getMessage())) {
                LogUtils.e(e.toString());
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            tvMeCash.setText("获取失败");
        }
        @Override
        public void onComplete() {
        }
    });
}
 
Example 28
Project: DeepImagePreview-Project   File: TabActivity.java   Source Code and License 5 votes vote down vote up
private void registerWithEventBusOnMainThread() {
    Disposable disposable = RxBus.getInstance().toObservable()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Object>() {
                @Override
                public void accept(Object o) throws Exception {

                }
            });

    mCompositeDisposable.add(disposable);
}
 
Example 29
Project: GmArchMvvm   File: RtoViewModel.java   Source Code and License 5 votes vote down vote up
LiveData<List<TextContent>> getSearchDataBySort(int start, int end, int search, int sort) {
        if (mContents == null)
            mContents = new MutableLiveData<>();

        if (mData == null)
            mData = new ArrayList<>();


        mModel.getSortedData(start, end, search, sort)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<List<TextContent>>(
                                   RepositoryUtils.INSTANCE.obtainRepositoryComponent(getApplication()).rxErrorHandler()) {
                               @Override
                               public void onSubscribe(Disposable d) {
                                   super.onSubscribe(d);
                                   addDispose(d);
                               }

                               @Override
                               public void onNext(List<TextContent> textContents) {
//                                   mContents.setValue(textContents);
                                   mContents.postValue(textContents);
                               }

                               @Override
                               public void onError(Throwable e) {
                                   super.onError(e);
                               }
                           }
                );


        return mContents;
    }
 
Example 30
Project: RxDisposal   File: SubscriptionDecoratorTest.java   Source Code and License 5 votes vote down vote up
private void validateOnSubscribe(Observer<? super String> testObserver) throws Exception {
    final Disposable testDisposable = mock(Disposable.class);
    testObserver.onSubscribe(testDisposable);
    verify(mockOnSusbcribe, times(1))
            .accept(argThat(validateDisposeIsDelegated(testDisposable)));

}
 
Example 31
Project: RxSWT   File: EclipseScheduler.java   Source Code and License 5 votes vote down vote up
@Override
public Disposable scheduleDirect(Runnable run, long delay, TimeUnit unit) {
	if (run == null)
		throw new NullPointerException("run == null");
	if (unit == null)
		throw new NullPointerException("unit == null");

	run = RxJavaPlugins.onSchedule(run);

	ScheduledRunnable scheduled = new ScheduledRunnable(run);

	executeRunnable(jobName, delay, unit, scheduled);

	return scheduled;
}
 
Example 32
Project: KomaMusic   File: RecentlyPlayPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void loadRecentlyPlayedSongs() {
    if (mDisposables != null) {
        mDisposables.clear();
    }

    Disposable disposable = mRepository.getRecentlyPlayedSongs().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableSubscriber<List<Song>>() {
                @Override
                public void onError(Throwable e) {
                    LogUtils.e(TAG, "loadRecentlyPlayedSongs error : " + e.toString());
                }

                @Override
                public void onComplete() {

                }

                @Override
                public void onNext(List<Song> songs) {
                    onLoadPlayedSongsFinished(songs);
                }
            });

    mDisposables.add(disposable);
}
 
Example 33
Project: SlotNSlot_Android   File: RxSlotRoom.java   Source Code and License 5 votes vote down vote up
private void setBankerSeedInitializedEvent() {
    Disposable disposable = machine
            .bankerSeedInitializedEventObservable()
            .subscribe(response -> {
                Log.i(TAG, "banker seed initialized.");
                Log.i(TAG, "banker seed1 : " + Utils.byteToHex(response._bankerSeed.getValue().get(0).getValue()));
                Log.i(TAG, "banker seed2 : " + Utils.byteToHex(response._bankerSeed.getValue().get(1).getValue()));
                Log.i(TAG, "banker seed3 : " + Utils.byteToHex(response._bankerSeed.getValue().get(2).getValue()));
            }, Throwable::printStackTrace);
    compositeDisposable.add(disposable);
}
 
Example 34
Project: DeepImagePreview-Project   File: ScanPresenter.java   Source Code and License 5 votes vote down vote up
private void registerEvents() {
    Disposable disposable = RxBus.getInstance()
            .toObservable()
            .subscribeOn(Schedulers.newThread())
            .subscribe(new Consumer<Object>() {
                @Override
                public void accept(Object o) throws Exception {

                    if (o instanceof PageChangedEvent) {
                        handlePageChangedEvent((PageChangedEvent) o);
                    }
                }
            });
    mCompositeDisposable.add(disposable);
}
 
Example 35
Project: AssistantBySDK   File: MemoActivity.java   Source Code and License 5 votes vote down vote up
private void loadData() {
    Observable.create(new ObservableOnSubscribe<Integer>() {
        @Override
        public void subscribe(ObservableEmitter<Integer> e) throws Exception {
            List<Memo> memos = mAssistDao.findAllMemoDesc(false);
            for (Memo memo : memos) {
                mDatas.add(new TaskCard<>(memo, TaskCard.TaskState.ACTIVE));
            }
            memoCount = memos.size();
            e.onNext(0);
        }
    })
            .subscribeOn(Schedulers.io())
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(Disposable disposable) throws Exception {
                    mCpbLoad.setVisibility(View.VISIBLE);
                }
            })
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<Integer>() {
                @Override
                public void accept(Integer integer) throws Exception {
                    mCpbLoad.setVisibility(View.GONE);
                    mMemoAdapter.notifyDataSetChanged();

                }
            });
}
 
Example 36
Project: RxJava2-Android-Sample   File: NetworkingActivity.java   Source Code and License 5 votes vote down vote up
private void findUsersWhoLovesBoth() {
    // here we are using zip operator to combine both request
    Observable.zip(getCricketFansObservable(), getFootballFansObservable(),
            new BiFunction<List<User>, List<User>, List<User>>() {
                @Override
                public List<User> apply(List<User> cricketFans, List<User> footballFans) throws Exception {
                    List<User> userWhoLovesBoth =
                            filterUserWhoLovesBoth(cricketFans, footballFans);
                    return userWhoLovesBoth;
                }
            })
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<User>>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(List<User> users) {
                    // do anything with user who loves both
                    Log.d(TAG, "userList size : " + users.size());
                    for (User user : users) {
                        Log.d(TAG, "user : " + user.toString());
                    }
                }

                @Override
                public void onError(Throwable e) {
                    Utils.logError(TAG, e);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example 37
Project: GitHub   File: RxTiPresenterDisposableHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testManageViewDisposable_ShouldReturnSameDisposable() throws Exception {
    mPresenter.create();
    mPresenter.attachView(mView);
    final TestObserver<Integer> testObserver = new TestObserver<>();

    final Disposable disposable = mDisposableHandler.manageViewDisposable(testObserver);

    assertThat(testObserver, is(equalTo(disposable)));
}
 
Example 38
Project: KomaMusic   File: AlbumsPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void loadAlbums() {
    LogUtils.i(TAG, "loadAlbums");

    mDisposables.clear();

    Disposable disposable = mRepository.getAllAlbums().subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableSubscriber<List<Album>>() {
                @Override
                public void onError(Throwable throwable) {
                    LogUtils.e(TAG, "loadAlbums onError : " + throwable.toString());
                }

                @Override
                public void onComplete() {

                }

                @Override
                public void onNext(List<Album> albumList) {
                    onLoadSongsFinished(albumList);
                }
            });

    mDisposables.add(disposable);
}
 
Example 39
Project: GitHub   File: PaginationActivity.java   Source Code and License 5 votes vote down vote up
/**
 * subscribing for data
 */
private void subscribeForData() {

    Disposable disposable = paginator
            .onBackpressureDrop()
            .concatMap(new Function<Integer, Publisher<List<String>>>() {
                @Override
                public Publisher<List<String>> apply(@NonNull Integer page) throws Exception {
                    loading = true;
                    progressBar.setVisibility(View.VISIBLE);
                    return dataFromNetwork(page);
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<List<String>>() {
                @Override
                public void accept(@NonNull List<String> items) throws Exception {
                    paginationAdapter.addItems(items);
                    paginationAdapter.notifyDataSetChanged();
                    loading = false;
                    progressBar.setVisibility(View.INVISIBLE);
                }
            });

    compositeDisposable.add(disposable);

    paginator.onNext(pageNumber);

}
 
Example 40
Project: rxgwt-tips   File: Pokeapi.java   Source Code and License 5 votes vote down vote up
static Disposable showPokemons() {
    return fromPromise(Notification.requestPermission()).filter("granted"::equals).toFlowable()
            .concatMap(n -> pokePaging("https://pokeapi.co/api/v2/pokemon/?limit=5"), 1)
            .zipWith(interval(5, 30, TimeUnit.SECONDS), (url, tick) -> url, false, 1)
            .flatMapSingle(n -> fetchJson(n.url, Pokemon.class))
            .subscribe(n -> {
                NotificationOptions options = Js.uncheckedCast(JsPropertyMap.of());
                options.icon = n.sprites.front_default;
                options.body = "Do you know that " + n.name + " weight is " + n.weight + ".";
                new Notification(n.name, options);
            });
}
 
Example 41
Project: GitHub   File: DebounceExampleActivity.java   Source Code and License 5 votes vote down vote up
private Observer<Integer> getObserver() {
    return new Observer<Integer>() {

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

        @Override
        public void onNext(Integer value) {
            textView.append(" onNext : ");
            textView.append(AppConstant.LINE_SEPARATOR);
            textView.append(" value : " + value);
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onNext ");
            Log.d(TAG, " value : " + value);
        }

        @Override
        public void onError(Throwable e) {
            textView.append(" onError : " + e.getMessage());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onError : " + e.getMessage());
        }

        @Override
        public void onComplete() {
            textView.append(" onComplete");
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onComplete");
        }
    };
}
 
Example 42
Project: RabbitCloud   File: LiveTypeDetailPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void getLiveTypeData(String cate, int pageno, final int pagenum) {
    Disposable disposable = mRabbitApi.getRoomInfoByCate(cate, pageno, pagenum)
            .map(new Function<LiveRoomListBean, LiveRoomListBean.DataBean>() {
                @Override
                public LiveRoomListBean.DataBean apply(LiveRoomListBean liveRoomListBean) {
                    return liveRoomListBean.getData();
                }
            })
            .subscribe(new Consumer<LiveRoomListBean.DataBean>() {
                @Override
                public void accept(@NonNull LiveRoomListBean.DataBean dataBean) throws Exception {
                    if (dataBean != null && mView != null) {
                        if (dataBean.getBanners() != null) {
                            List<LiveRoomListBean.DataBean.BannersBean> bannersData =
                                    dataBean.getBanners();
                            mView.showLiveTypeBannerData(bannersData);
                        }

                        List<LiveRoomListBean.DataBean.ItemsBean> itemsData =
                                dataBean.getItems();
                        mView.showLiveTypeItemsData(itemsData);
                    }
                }
            });
    addDisposable(disposable);
}
 
Example 43
Project: AmenEye   File: ZhihuStoryInfoPresenter.java   Source Code and License 5 votes vote down vote up
public void loadStory(String id) {
    mActivity.showProgressBar();
    ApiManager.getInstence().getZhihuService().getStoryContent(id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<ZhihuStoryContent>() {

                @Override
                public void onError(Throwable e) {
                    mActivity.loadFail(e.getMessage());
                    mActivity.hideProgressBar();
                }

                @Override
                public void onComplete() {
                    mActivity.hideProgressBar();
                }

                @Override
                public void onSubscribe(Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onNext(ZhihuStoryContent zhihuStoryContent) {
                    mActivity.loadSuccess(zhihuStoryContent);
                    mActivity.hideProgressBar();
                }
            });

}
 
Example 44
Project: RxJava2-Android-Sample   File: DelayExampleActivity.java   Source Code and License 5 votes vote down vote up
private Observer<String> getObserver() {
    return new Observer<String>() {

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

        @Override
        public void onNext(String value) {
            textView.append(" onNext : value : " + value);
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onNext : value : " + value);
        }

        @Override
        public void onError(Throwable e) {
            textView.append(" onError : " + e.getMessage());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onError : " + e.getMessage());
        }

        @Override
        public void onComplete() {
            textView.append(" onComplete");
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onComplete");
        }
    };
}
 
Example 45
Project: RxJava2-Android-Sample   File: BehaviorSubjectExampleActivity.java   Source Code and License 5 votes vote down vote up
private Observer<Integer> getSecondObserver() {
    return new Observer<Integer>() {

        @Override
        public void onSubscribe(Disposable d) {
            textView.append(" Second onSubscribe : isDisposed :" + d.isDisposed());
            Log.d(TAG, " Second onSubscribe : " + d.isDisposed());
            textView.append(AppConstant.LINE_SEPARATOR);
        }

        @Override
        public void onNext(Integer value) {
            textView.append(" Second onNext : value : " + value);
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " Second onNext value : " + value);
        }

        @Override
        public void onError(Throwable e) {
            textView.append(" Second onError : " + e.getMessage());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " Second onError : " + e.getMessage());
        }

        @Override
        public void onComplete() {
            textView.append(" Second onComplete");
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " Second onComplete");
        }
    };
}
 
Example 46
Project: Reactive-Programming-With-Java-9   File: Demo_defaultIfEmpty.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
		// TODO Auto-generated method stub
		Observable.empty().defaultIfEmpty(100).
        subscribe(new Observer() {

			@Override
			public void onComplete() {
				// TODO Auto-generated method stub
				System.out.println("the sequence got completed");
			}

			@Override
			public void onError(Throwable throwable) {
				// TODO Auto-generated method stub
				throwable.printStackTrace();
			}
			@Override
			public void onNext(Object value) {
				// TODO Auto-generated method stub
				System.out.println("emitted:-"+value);
				
			}

			@Override
			public void onSubscribe(Disposable disposable) {
				// TODO Auto-generated method stub
				System.out.println(disposable.isDisposed());
				
			}
});


	}
 
Example 47
Project: Rx2Animations   File: ColorPickerPresenter.java   Source Code and License 5 votes vote down vote up
@Override
public void refreshView() {
    final ColorPickerContract.View view = getNullableView();
    if (view == null) {
        return;
    }

    final Disposable animationDisposable = view.setupInitialAnimation()
            .delay(500, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .concatWith(view.startInitialAnimation())
            .subscribe(this::onAnimationEnd, Throwable::printStackTrace);

    addSubscription(animationDisposable);
}
 
Example 48
Project: GitHub   File: ReplaySubjectExampleActivity.java   Source Code and License 5 votes vote down vote up
private Observer<Integer> getSecondObserver() {
    return new Observer<Integer>() {

        @Override
        public void onSubscribe(Disposable d) {
            textView.append(" Second onSubscribe : isDisposed :" + d.isDisposed());
            Log.d(TAG, " Second onSubscribe : " + d.isDisposed());
            textView.append(AppConstant.LINE_SEPARATOR);
        }

        @Override
        public void onNext(Integer value) {
            textView.append(" Second onNext : value : " + value);
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " Second onNext value : " + value);
        }

        @Override
        public void onError(Throwable e) {
            textView.append(" Second onError : " + e.getMessage());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " Second onError : " + e.getMessage());
        }

        @Override
        public void onComplete() {
            textView.append(" Second onComplete");
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " Second onComplete");
        }
    };
}
 
Example 49
Project: reactive-architectures-playground   File: DisposeStrategyTests.java   Source Code and License 5 votes vote down vote up
@Test public void shouldDispose_OnDestroy() {
    DisposeStrategy strategy = new DisposeStrategy();
    Disposable target = Flowable.just("A", "B", "C").subscribe();
    strategy.addDisposable(target);
    strategy.onDestroy();
    assertThat(target.isDisposed()).isTrue();

}
 
Example 50
Project: NovelReader   File: BookSortListFragment.java   Source Code and License 5 votes vote down vote up
@Override
protected void initClick() {
    super.initClick();
    mBookSortListAdapter.setOnItemClickListener(
            (view, pos) -> {
                String bookId = mBookSortListAdapter.getItem(pos).get_id();
                BookDetailActivity.startActivity(getContext(),bookId);
            }
    );

    mBookSortListAdapter.setOnLoadMoreListener(
            () -> mPresenter.loadSortBook(mGender,mType,mMajor,mMinor,mStart,mLimit)
    );

    //子类的切换
    Disposable disposable = RxBus.getInstance()
            .toObservable(BookSubSortEvent.class)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                    (event) -> {
                        mMinor = event.bookSubSort;
                        mRefreshLayout.showLoading();
                        mStart = 0;
                        mPresenter.refreshSortBook(mGender,mType,mMajor,mMinor,mStart,mLimit);
                    }
            );
    addDisposable(disposable);
}
 
Example 51
Project: rxjava2   File: BeerClient.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {

        Observable<Beer> beerData = BeerServer.getData(); // No streaming just yet
                  
        Observer beerObserver = new Observer<Beer>() {

            public void onSubscribe(Disposable d) {
                System.out.println( " !!! Someone just subscribed to the bear stream!!! ");

                // If the subscriber is less than 21 year old, cancel subscription
                // d.dispose();
            }

            public void onNext(Beer beer) {
                System.out.println(beer);
            }

            public void onError(Throwable throwable) {
                System.err.println("In Observer.onError(): " + throwable.getMessage());
            }

            public void onComplete() {
                System.out.println("*** The stream is over ***");
            }
        };
        
        beerData
            .subscribe(beerObserver);       // Streaming starts here
    }
 
Example 52
Project: Reactive-Programming-With-Java-9   File: Demo_take_no_threading.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Observable<Integer> observable = Observable.range(1, 50);

	observable.take(5).subscribe(new Observer<Integer>() {

		@Override
		public void onComplete() {
			// TODO Auto-generated method stub
			System.out.println(Thread.currentThread().getName() + " finished reading of items");

		}

		@Override
		public void onError(Throwable throwable) {
			// TODO Auto-generated method stub
			System.out.println(Thread.currentThread().getName() + " finished with exception");

		}

		@Override
		public void onNext(Integer value) {
			// TODO Auto-generated method stub
			System.out.println(Thread.currentThread().getName() + " read item:-"+value);

		}

		@Override
		public void onSubscribe(Disposable arg0) {
			// TODO Auto-generated method stub

		}
	});

}
 
Example 53
Project: Acg   File: CopyDetailsActivity.java   Source Code and License 5 votes vote down vote up
private void loadData() {

        Disposable subscribe = RetrofitHelper.createCopyService()
                .getCopyDetails(activityId, "d89a68bddc0784e750f6f841eeb61647#")
                .doOnSubscribe(subscription -> {
                    mCircleProgress.setVisibility(View.VISIBLE);
                    mCircleProgress.spin();
                    mRecyclerView.setVisibility(View.GONE);
                })
                .filter(copyDetailsInfoBaseResponseInfo -> copyDetailsInfoBaseResponseInfo.getCode().equals(AppConstant.SUCCESS_CODE))
                .map(CopyDetailsInfo::getResult)
                .flatMap(new Function<CopyDetailsInfo.ResultBean, Publisher<BaseResponseInfo<QuanziInfo>>>() {
                    @Override
                    public Publisher<BaseResponseInfo<QuanziInfo>> apply(CopyDetailsInfo.ResultBean resultBean) throws Exception {
                        copyDetailsResult = resultBean;
                        return RetrofitHelper.createQuanziService()
                                .getQuanziInfos(-1, Long.valueOf(activityId), -1, 8, -1, -1, "dbe5b18fe665dbc25d22cdeb2d5cc436#");
                    }
                })
                .map(BaseResponseInfo::getBaseResult)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(quanziInfo -> {
                    blogList.addAll(quanziInfo.getBlogList());
                    mCircleProgress.setVisibility(View.GONE);
                    mCircleProgress.stopSpinning();
                    mRecyclerView.setVisibility(View.VISIBLE);
                    finishTask();
                }, throwable -> Log.e("tag", throwable.getMessage()));

        compositeDisposable.add(subscribe);
    }
 
Example 54
Project: AcopioMX   File: Presenter.java   Source Code and License 5 votes vote down vote up
@Override
public void login(String email, String username, String password) {
    view.showProgressBar();
    if (retroService != null) {
        Observable<Login.Result> result = retroService
                .login(new Login(email, username, password));
        if (result != null) {
            result.subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Login.Result>() {
                        @Override
                        public void onSubscribe(Disposable d) { }

                        @Override
                        public void onNext(Login.Result s) {
                            view.hideProgressBar();
                            if (s == null) {
                                view.showError("Could not login, please try again");
                                return;
                            }
                            view.setupId(s.getId());
                        }

                        @Override
                        public void onError(Throwable e) {
                            view.hideProgressBar();
                            view.showError(e.getLocalizedMessage());
                            Log.d("LOGIN", "---> error: "+e.getLocalizedMessage());
                        }

                        @Override
                        public void onComplete() { }
                    });
        }
    }
}
 
Example 55
Project: GitHub   File: StatisticsPresenter.java   Source Code and License 5 votes vote down vote up
private void loadStatistics() {
    mStatisticsView.setProgressIndicator(true);

    // The network request might be handled in a different thread so make sure Espresso knows
    // that the app is busy until the response is handled.
    EspressoIdlingResource.increment(); // App is busy until further notice

    Flowable<Task> tasks = mTasksRepository
            .getTasks()
            .flatMap(Flowable::fromIterable);
    Flowable<Long> completedTasks = tasks.filter(Task::isCompleted).count().toFlowable();
    Flowable<Long> activeTasks = tasks.filter(Task::isActive).count().toFlowable();
    Disposable disposable = Flowable
            .zip(completedTasks, activeTasks, (completed, active) -> Pair.create(active, completed))
            .subscribeOn(mSchedulerProvider.computation())
            .observeOn(mSchedulerProvider.ui())
            .doFinally(() -> {
                if (!EspressoIdlingResource.getIdlingResource().isIdleNow()) {
                    EspressoIdlingResource.decrement(); // Set app as idle.
                }
            })
            .subscribe(
                    // onNext
                    stats -> mStatisticsView.showStatistics(Ints.saturatedCast(stats.first), Ints.saturatedCast(stats.second)),
                    // onError
                    throwable -> mStatisticsView.showLoadingStatisticsError(),
                    // onCompleted
                    () -> mStatisticsView.setProgressIndicator(false));
    mCompositeDisposable.add(disposable);
}
 
Example 56
Project: RxJava2-Android-Sample   File: AndThenWhenExampleActivity.java   Source Code and License 5 votes vote down vote up
private Observer<String> getObserver() {
    return new Observer<String>() {

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

        @Override
        public void onNext(String value) {
            textView.append(" onNext : value : " + value);
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onNext : value : " + value);
        }

        @Override
        public void onError(Throwable e) {
            textView.append(" onError : " + e.getMessage());
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onError : " + e.getMessage());
        }

        @Override
        public void onComplete() {
            textView.append(" onComplete");
            textView.append(AppConstant.LINE_SEPARATOR);
            Log.d(TAG, " onComplete");
        }
    };
}
 
Example 57
Project: ZhaZhaShop   File: MovieTop100Activity.java   Source Code and License 5 votes vote down vote up
public void getTopHundredMovie() {
    RetrofitClient.getInstance()
            .apiMovieRankService()
            .getTopHundredMovie(10, offset)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<TopHundredMovieBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    showLoading();
                }

                @Override
                public void onNext(@NonNull TopHundredMovieBean topHundredMovieBean) {
                    addContent(topHundredMovieBean.getData().getCreated(), topHundredMovieBean.getData().getContent());
                    addTopHundredMovie(topHundredMovieBean.getData().getMovies());
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    showError(ErrorHanding.handleError(e));
                }

                @Override
                public void onComplete() {
                    showContent();
                }
            });
}
 
Example 58
Project: RxLifecycle   File: RxAppCompatActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Dispose a subscriber on alternative event
 *
 * @param disposable
 */
public final void dispose(Disposable disposable) {
    final ActivityEvent lastEvent = this.lastEvent;
    ActivityEvent event = null;
    switch (lastEvent) {
        case CREATE:
            event = ActivityEvent.DESTROY;
            break;

        case START:
            event = ActivityEvent.STOP;
            break;

        case RESUME:
            event = ActivityEvent.PAUSE;
            break;

        case PAUSE:
            event = ActivityEvent.STOP;
            break;

        case STOP:
            event = ActivityEvent.DESTROY;
            break;

        default:
            throw new UnsupportedOperationException(String.format("Event can't be disposed at eventType : %s", lastEvent.name()));
    }

    this.dispose(disposable, event);
}
 
Example 59
Project: GitHub   File: RxCommonActivity.java   Source Code and License 5 votes vote down vote up
@OnClick(R.id.upString)
public void upString(View view) {
    OkGo.<String>post(Urls.URL_TEXT_UPLOAD)//
            .headers("aaa", "111")//
            .upString("上传的文本。。。")//
            .converter(new StringConvert())//
            .adapt(new ObservableResponse<String>())//
            .subscribeOn(Schedulers.io())//
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(@NonNull Disposable disposable) throws Exception {
                    showLoading();
                }
            })//
            .observeOn(AndroidSchedulers.mainThread())//
            .subscribe(new Observer<Response<String>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onNext(@NonNull Response<String> response) {
                    handleResponse(response);
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    e.printStackTrace();
                    showToast("请求失败");
                    handleError(null);
                }

                @Override
                public void onComplete() {
                    dismissLoading();
                }
            });
}
 
Example 60
Project: Reactive-Programming-With-Java-9   File: Demo_ignoreElements.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
	// TODO Auto-generated method stub
	String[] fruits = { "mango", "pineapple", "apple", "mango", "papaya" };
	Observable.fromArray(fruits).ignoreElements().subscribe(
		new CompletableObserver() {
		long time=0;
		@Override
		public void onSubscribe(Disposable disposable) {
			// TODO Auto-generated method stub
			time=System.currentTimeMillis();
			System.out.println(disposable.isDisposed()+"\t"+time);
			
			
		}
		@Override
		public void onError(Throwable throwable) {
			// TODO Auto-generated method stub
			throwable.printStackTrace();
		}
		
		@Override
		public void onComplete() {
			// TODO Auto-generated method stub
			System.out.println("completed");
			long time_to_complete=System.currentTimeMillis()-time;
			System.out.println("process completedin: "+time_to_complete+"ms");
			
		}
	});
			


}