io.reactivex.SingleObserver Java Examples

The following examples show how to use io.reactivex.SingleObserver. 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: MaybeConsumers.java    From science-journal with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the opposite translation from {@link
 * MaybeConsumers#fromSingleObserver(SingleObserver)}
 */
public static <T> SingleObserver<T> toSingleObserver(final MaybeConsumer<T> c) {
  return new SingleObserver<T>() {
    @Override
    public void onSubscribe(@NonNull Disposable d) {
      // do nothing
    }

    @Override
    public void onSuccess(@NonNull T t) {
      c.success(t);
    }

    @Override
    public void onError(@NonNull Throwable e) {
      c.fail(new RuntimeException(e));
    }
  };
}
 
Example #2
Source File: MemberSingle.java    From rxjava2-jdbc with Apache License 2.0 6 votes vote down vote up
@Override
protected void subscribeActual(SingleObserver<? super Member<T>> observer) {
    // the action of checking out a member from the pool is implemented as a
    // subscription to the singleton MemberSingle
    MemberSingleObserver<T> m = new MemberSingleObserver<T>(observer, this);
    observer.onSubscribe(m);
    if (pool.isClosed()) {
        observer.onError(new PoolClosedException());
        return;
    }
    add(m);
    if (m.isDisposed()) {
        remove(m);
    } else {
        // atomically change requested
        while (true) {
            Observers<T> a = observers.get();
            if (observers.compareAndSet(a, a.withRequested(a.requested + 1))) {
                break;
            }
        }
    }
    log.debug("subscribed");
    drain();
}
 
Example #3
Source File: PermPresenter.java    From AppOpsX with MIT License 6 votes vote down vote up
void reset(){
  Helper.resetMode(context, appInfo.packageName)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new SingleObserver<OpsResult>(){

        @Override
        public void onSubscribe(@NonNull Disposable d) {

        }

        @Override
        public void onSuccess(@NonNull OpsResult opsResult) {
          load();
        }

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

        }
      });
}
 
Example #4
Source File: ArticleFragment.java    From hex with Apache License 2.0 6 votes vote down vote up
private void loadArticle() {
    SingleObserver observer = new SingleObserver<Story>() {
        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onSuccess(Story story) {
            mWebView.loadUrl(story.getUrl());
            hideArticleUnavailable();
        }

        @Override
        public void onError(Throwable e) {
            showArticleUnavailable();
            mSwipeRefreshLayout.setRefreshing(false);
        }
    };

    getStory().subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(observer);
}
 
Example #5
Source File: StoryActivity.java    From hex with Apache License 2.0 6 votes vote down vote up
private void loadArticleTitle() {
    SingleObserver observer = new SingleObserver<Story>() {
        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onSuccess(Story story) {
            getSupportActionBar().setTitle(story.getTitle());
        }

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

    mGetStory.subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(observer);
}
 
Example #6
Source File: OperatorActivity.java    From android-open-framework-analysis with Apache License 2.0 6 votes vote down vote up
private void single() {
    Single.just(1).subscribe(new SingleObserver<Integer>() {
        @Override
        public void onSubscribe(Disposable d) {
            Log.d(TAG, "onSubscribe: " + d.isDisposed());
        }

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

        @Override
        public void onError(Throwable e) {

        }
    });
}
 
Example #7
Source File: RxJava2FutureUtils.java    From future-converter with Apache License 2.0 6 votes vote down vote up
@Override
protected void subscribeActual(SingleObserver<? super T> observer) {
    ValueSourceDisposable disposable = new ValueSourceDisposable();
    valueSource.addCallbacks(
        result -> {
            try {
                observer.onSuccess(result);
            } catch (Throwable e) {
                observer.onError(e);
            }
        },
        ex -> {
            if (!disposable.isDisposed()) {
                observer.onError(ex);
            }
        }
    );
    observer.onSubscribe(disposable);
}
 
Example #8
Source File: PermPresenter.java    From AppOpsX with MIT License 6 votes vote down vote up
void autoDisable() {
  Helper.autoDisable(context, appInfo.packageName)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new SingleObserver<SparseIntArray>() {

        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onSuccess(SparseIntArray value) {
          autoDisabled = true;
          load();
        }

        @Override
        public void onError(Throwable e) {
          autoDisabled = true;
          load();
        }
      });
}
 
Example #9
Source File: SearchPresenter.java    From JReadHub with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void addHistory(SearchHistoryBean newDataBean) {
    mDataManager.getSingleHistory(newDataBean.getKeyWord())
            .compose(RxSchedulers.singleIo2Main())
            .subscribe(new SingleObserver<SearchHistoryBean>() {
                @Override
                public void onSubscribe(Disposable d) {
                    addSubscribe(d);
                }

                @Override
                public void onSuccess(SearchHistoryBean oldDataBean) {
                    oldDataBean.setTime(newDataBean.getTime());
                    updateHistory(oldDataBean);
                }

                @Override
                public void onError(Throwable e) {
                    if (e instanceof EmptyResultSetException) {
                        mDataManager.insert(newDataBean);
                    }
                }
            });
}
 
Example #10
Source File: SingleHelper.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
/**
 * Adapts an Vert.x {@code Handler<AsyncResult<T>>} to an RxJava2 {@link SingleObserver}.
 * <p>
 * The returned observer can be subscribed to an {@link Single#subscribe(SingleObserver)}.
 *
 * @param handler the handler to adapt
 * @return the observer
 */
public static <T> SingleObserver<T> toObserver(Handler<AsyncResult<T>> handler) {
  AtomicBoolean completed = new AtomicBoolean();
  return new SingleObserver<T>() {
    @Override
    public void onSubscribe(@NonNull Disposable d) {
    }
    @Override
    public void onSuccess(@NonNull T item) {
      if (completed.compareAndSet(false, true)) {
        handler.handle(Future.succeededFuture(item));
      }
    }
    @Override
    public void onError(Throwable error) {
      if (completed.compareAndSet(false, true)) {
        handler.handle(Future.failedFuture(error));
      }
    }
  };
}
 
Example #11
Source File: NavDrawerFragment.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
private void postUread(String boardName, long threadId, @NonNull UnreadCountUpdate callback) {
    HistoryTableConnection.fetchPost(boardName, threadId)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SingleObserver<History>() {
                @Override
                public void onSubscribe(Disposable d) {
                    // no op
                }

                @Override
                public void onSuccess(History history) {
                    callback.OnUnreadCountUpdate(history.unreadCount);
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(LOG_TAG, "Error setting unread count badge", e);
                }
            });
}
 
Example #12
Source File: LeaderboardBar.java    From 1Rramp-Android with MIT License 6 votes vote down vote up
/**
 * fetch leaderboard
 */
private void loadLeaders() {
  RetrofitServiceGenerator.getService().getLeaderboardList()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribeWith(new SingleObserver<LeaderboardModel>() {
      @Override
      public void onSubscribe(Disposable d) {
        compositeDisposable.add(d);
      }

      @Override
      public void onSuccess(LeaderboardModel leaderboardModel) {
        handleLeaderBoardList(leaderboardModel);
      }

      @Override
      public void onError(Throwable e) {
      }
    });
}
 
Example #13
Source File: ExampleUnitTest.java    From RxAndroid-Sample with Apache License 2.0 6 votes vote down vote up
@Test
public void testContainsObservable() {

    Observable.just(1, 2, 3, 4, 5, 6)
            .contains(10)
            .subscribe(new SingleObserver<Boolean>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onSuccess(Boolean aBoolean) {
                    System.out.println("Does list contain value 10: " + aBoolean);
                }

                @Override
                public void onError(Throwable e) {

                }
            });
}
 
Example #14
Source File: ExampleUnitTest.java    From RxAndroid-Sample with Apache License 2.0 6 votes vote down vote up
@Test
public void testCountObservable() {

    Observable.just(1, 2, 3, 4, 5)
            .count()
            .subscribe(new SingleObserver<Long>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onSuccess(Long aLong) {
                    System.out.println("Count: " + aLong);
                }

                @Override
                public void onError(Throwable e) {

                }
            });
}
 
Example #15
Source File: MainActivity.java    From AppOpsX with MIT License 6 votes vote down vote up
private void loadUsers(){
  Helper.getUsers(getApplicationContext(),true).subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new SingleObserver<List<UserInfo>>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onSuccess(List<UserInfo> userInfos) {

          Users.getInstance().updateUsers(userInfos);
          invalidateOptionsMenu();
        }

        @Override
        public void onError(Throwable e) {

        }
      });
}
 
Example #16
Source File: SettingsActivity.java    From AppOpsX with MIT License 6 votes vote down vote up
private void closeServer() {
  Helper.closeBgServer(getActivity().getApplicationContext()).subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread()).subscribe(new SingleObserver<Boolean>() {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onSuccess(Boolean value) {
      Activity activity = getActivity();
      if (activity != null) {
        Toast.makeText(activity, R.string.bg_closed, Toast.LENGTH_SHORT).show();
      }
    }

    @Override
    public void onError(Throwable e) {

    }
  });
}
 
Example #17
Source File: AppInstalledReceiver.java    From AppOpsX with MIT License 6 votes vote down vote up
private void showDlg(final Context context, String pkg) {
  Helper.getAppInfo(context, pkg)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new SingleObserver<AppInfo>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onSuccess(AppInfo value) {
          Intent intent = new Intent(context, AlertInstalledPremActivity.class);
          intent.putExtra(AlertInstalledPremActivity.EXTRA_APP, value);
          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
          context.startActivity(intent);
        }

        @Override
        public void onError(Throwable e) {

        }
      });
}
 
Example #18
Source File: SubscribeOnlyOnceSingleOperator.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public SingleObserver<? super T> apply(final SingleObserver<? super T> observer) {
    return new SingleObserver<T>() {
        @Override
        public void onSubscribe(Disposable d) {
            if (subscribedOnce.getAndSet(true)) {
                throw new NullPointerException("You cannot directly subscribe to a gRPC service multiple times " +
                        "concurrently. Use Flowable.share() instead.");
            } else {
                observer.onSubscribe(d);
            }
        }

        @Override
        public void onSuccess(T t) {
            observer.onSuccess(t);
        }

        @Override
        public void onError(Throwable e) {
            observer.onError(e);
        }
    };
}
 
Example #19
Source File: SubscribeOnlyOnceTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void subscribeOnlyOnceSingleOperatorErrorsWhenMultipleSubscribe() {
    SubscribeOnlyOnceSingleOperator<Object> op = new SubscribeOnlyOnceSingleOperator<Object>();
    SingleObserver<Object> innerSub = mock(SingleObserver.class);
    final Disposable disposable = mock(Disposable.class);

    final SingleObserver<Object> outerSub = op.apply(innerSub);

    outerSub.onSubscribe(disposable);
    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() {
            outerSub.onSubscribe(disposable);
        }
    })
            .isInstanceOf(NullPointerException.class)
            .hasMessageContaining("cannot directly subscribe to a gRPC service multiple times");

    verify(innerSub, times(1)).onSubscribe(disposable);
}
 
Example #20
Source File: RXTestBase.java    From vertx-jooq with MIT License 6 votes vote down vote up
protected <T> SingleObserver<T> countdownLatchHandler(final CountDownLatch latch){
    return new SingleObserver<T>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onSuccess(T t) {
            latch.countDown();
        }

        @Override
        public void onError(Throwable x) {
            x.printStackTrace();
            Assert.fail(x.getMessage());
            latch.countDown();
        }
    };
}
 
Example #21
Source File: LastOperatorExampleActivity.java    From RxJava2-Android-Samples with Apache License 2.0 6 votes vote down vote up
private SingleObserver<String> getObserver() {
    return new SingleObserver<String>() {

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

        @Override
        public void onSuccess(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());
        }
    };
}
 
Example #22
Source File: SingleObserverExampleActivity.java    From RxJava2-Android-Samples with Apache License 2.0 6 votes vote down vote up
private SingleObserver<String> getSingleObserver() {
    return new SingleObserver<String>() {
        @Override
        public void onSubscribe(Disposable d) {
            Log.d(TAG, " onSubscribe : " + d.isDisposed());
        }

        @Override
        public void onSuccess(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());
        }
    };
}
 
Example #23
Source File: BookDetailPresenter.java    From NovelReader with MIT License 6 votes vote down vote up
private void refreshBook(){
    RemoteRepository
            .getInstance()
            .getBookDetail(bookId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SingleObserver<BookDetailBean>() {
                @Override
                public void onSubscribe(Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onSuccess(BookDetailBean value){
                    mView.finishRefresh(value);
                    mView.complete();
                }

                @Override
                public void onError(Throwable e) {
                    mView.showError();
                }
            });
}
 
Example #24
Source File: FlowableExampleActivity.java    From RxJava2-Android-Samples with Apache License 2.0 6 votes vote down vote up
private SingleObserver<Integer> getObserver() {

        return new SingleObserver<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, " onSubscribe : " + d.isDisposed());
            }

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

            @Override
            public void onError(Throwable e) {
                textView.append(" onError : " + e.getMessage());
                textView.append(AppConstant.LINE_SEPARATOR);
                Log.d(TAG, " onError : " + e.getMessage());
            }
        };
    }
 
Example #25
Source File: PlayListPresenterImpl.java    From Android-AudioRecorder-App with Apache License 2.0 6 votes vote down vote up
@Override public void renameFile(int adapterPosition, String value) {
  rename(recordingItems.get(adapterPosition), adapterPosition, value).subscribe(
      new SingleObserver<Integer>() {
        @Override public void onSubscribe(Disposable d) {

        }

        @Override public void onSuccess(Integer position) {
          getAttachedView().notifyListItemChange(position);
        }

        @Override public void onError(Throwable e) {
          getAttachedView().showError(e.getMessage());
        }
      });
}
 
Example #26
Source File: ObserverUtil.java    From Learning-Resources with MIT License 6 votes vote down vote up
/**
 * @return SingleObserver with which observable will subscribe
 */
public static <T> SingleObserver<T> getSingleObserver(final CompositeDisposable compositeDisposable,
                                                      final WebserviceBuilder.ApiNames apiNames,
                                                      final SingleCallback tSingleCallback) {
    return new SingleObserver<T>() {

        @Override
        public void onSubscribe(Disposable d) {
            if (compositeDisposable != null) compositeDisposable.add(d);
        }

        @Override
        public void onSuccess(@NonNull T t) {
            if (tSingleCallback != null) tSingleCallback.onSingleSuccess(t, apiNames);
        }


        @Override
        public void onError(Throwable e) {
            if (tSingleCallback != null) tSingleCallback.onFailure(e, apiNames);
        }
    };
}
 
Example #27
Source File: MicroActivity.java    From J2ME-Loader with Apache License 2.0 6 votes vote down vote up
@SuppressLint("CheckResult")
private void takeScreenshot() {
	microLoader.takeScreenshot((Canvas) current)
			.subscribeOn(Schedulers.computation())
			.observeOn(AndroidSchedulers.mainThread())
			.subscribe(new SingleObserver<String>() {
				@Override
				public void onSubscribe(Disposable d) {
				}

				@Override
				public void onSuccess(String s) {
					Toast.makeText(MicroActivity.this, getString(R.string.screenshot_saved)
							+ " " + s, Toast.LENGTH_LONG).show();
				}

				@Override
				public void onError(Throwable e) {
					e.printStackTrace();
					Toast.makeText(MicroActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
				}
			});
}
 
Example #28
Source File: AppPermissionActivity.java    From AppOpsX with MIT License 6 votes vote down vote up
private void loadAppinfo(String pkgName){
  Helper.getAppInfo(getApplicationContext(),pkgName)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(new SingleObserver<AppInfo>() {
        @Override
        public void onSubscribe(@NonNull Disposable d) {

        }

        @Override
        public void onSuccess(@NonNull AppInfo appInfo) {
          setTitle(appInfo.appName);
        }

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

        }
      });
}
 
Example #29
Source File: HelperTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Test
public void testToSingleObserverFailure() {
  Promise<String> promise = Promise.promise();
  SingleObserver<String> observer = SingleHelper.toObserver(promise);
  RuntimeException cause = new RuntimeException();
  Single<String> s = Single.error(cause);
  s.subscribe(observer);
  assertTrue(promise.future().failed());
  assertSame(cause, promise.future().cause());
}
 
Example #30
Source File: MimiActivity.java    From mimi-reader with Apache License 2.0 5 votes vote down vote up
public void updateBadge(@DrawableRes final int navDrawable) {
    HistoryTableConnection.fetchHistory(true)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SingleObserver<List<History>>() {
                @Override
                public void onSubscribe(Disposable d) {
                    // no op
                }

                @Override
                public void onSuccess(List<History> histories) {

                    int unread = 0;
                    for (History history : histories) {
                        unread += history.unreadCount;
                    }

                    setNavigationIconWithBadge(navDrawable, unread);
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(LOG_TAG, "Error setting unread count badge", e);
                }
            });

}