本文整理汇总了Java中io.reactivex.Observable类的典型用法代码示例。如果您正苦于以下问题:Java Observable类的具体用法?Java Observable怎么用?Java Observable使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Observable类属于io.reactivex包,在下文中一共展示了Observable类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: searchData
import io.reactivex.Observable; //导入依赖的package包/类
private void searchData(String tag) {
mHintText.setText("");
mTagLayout.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
mSearchTag = tag;
Observable<GetDataBean> observable = mSearchApi.searchTagData(mSearchTag);
observable
.filter(new Predicate<GetDataBean>() {
@Override
public boolean test(@NonNull GetDataBean getDataBean) throws Exception {
return getDataBean != null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mObserver);
}
示例2: revokeToken
import io.reactivex.Observable; //导入依赖的package包/类
private Observable<JsonElement> revokeToken(AuthToken token, String clientSecret) {
// this complexity exists because the access token must be revoked AFTER the refresh token
// why? because the access token is needed for both revocations!
Subject<JsonElement> responses = PublishSubject.create();
RevokeReqBody refreshReqBody = RevokeReqBody.fromRefreshToken(
token.getRefreshToken(), clientSecret);
revokeSingleToken(token.getAuthHeader(), refreshReqBody, responses)
.doOnComplete(() -> {
RevokeReqBody accessReqBody = RevokeReqBody.fromAccessToken(
token.getAccessToken(), clientSecret);
revokeSingleToken(token.getAuthHeader(), accessReqBody, responses)
.subscribe();
})
.subscribe();
return responses;
}
示例3: main
import io.reactivex.Observable; //导入依赖的package包/类
public static void main(String[] args) {
Observable<String> source1 =
Observable.just("Alpha", "Beta");
Observable<String> source2 =
Observable.just("Gamma", "Delta");
Observable<String> source3 =
Observable.just("Epsilon", "Zeta");
Observable<String> source4 =
Observable.just("Eta", "Theta");
Observable<String> source5 =
Observable.just("Iota", "Kappa");
List<Observable<String>> sources =
Arrays.asList(source1, source2, source3, source4,
source5);
Observable.merge(sources)
.subscribe(i -> System.out.println("RECEIVED: " + i));
}
示例4: bindIntents
import io.reactivex.Observable; //导入依赖的package包/类
@Override protected void bindIntents() {
intent(ProductDetailsView::addToShoppingCartIntent)
.doOnNext(product -> Timber.d("intent: add to shopping cart %s", product))
.flatMap(product -> interactor.addToShoppingCart(product).toObservable()).subscribe();
intent(ProductDetailsView::removeFromShoppingCartIntent)
.doOnNext(product -> Timber.d("intent: remove from shopping cart %s", product))
.flatMap(product -> interactor.removeFromShoppingCart(product).toObservable())
.subscribe();
Observable<ProductDetailsViewState> loadDetails =
intent(ProductDetailsView::loadDetailsIntent)
.doOnNext(productId -> Timber.d("intent: load details for product id = %s", productId))
.flatMap(interactor::getDetails)
.observeOn(AndroidSchedulers.mainThread());
subscribeViewState(loadDetails, ProductDetailsView::render);
}
示例5: test_just_new
import io.reactivex.Observable; //导入依赖的package包/类
@Test
public void test_just_new() {
Observable<Integer> observable = Observable.just(12, 34, 6);
TestObserver<Integer> testObserver = new TestObserver<>();
observable.subscribe(testObserver);
List<Integer> list = new ArrayList();
testObserver.assertComplete();
testObserver.assertResult(12, 34, 6);
testObserver.assertValueCount(3);
testObserver.assertNoErrors();
testObserver.assertValueAt(2, (value) -> {
// TODO Auto-generated method stub
return value == 34;
});
}
示例6: test_interval
import io.reactivex.Observable; //导入依赖的package包/类
@Test
public void test_interval()
{
TestScheduler testScheduler=new TestScheduler();
Observable<Long>observable=Observable.interval(1, TimeUnit.SECONDS,testScheduler).take(5);
TestObserver<Long> testObserver=new TestObserver<>();
observable.subscribeOn(testScheduler).subscribe(testObserver);
testObserver.assertNoValues();
testObserver.assertNotComplete();
testObserver.assertNoErrors();
testScheduler.advanceTimeBy(1, TimeUnit.SECONDS);
testObserver.assertValueCount(1);
testObserver.assertValues(0l);
testScheduler.advanceTimeTo(6, TimeUnit.SECONDS);
testObserver.assertValueCount(5);
testObserver.assertValues(0l,1l,2l,3l,4l);
}
示例7: observable
import io.reactivex.Observable; //导入依赖的package包/类
/**
* The returned Observable emits Query results as Lists.
* Never completes, so you will get updates when underlying data changes.
*/
public static <T> Observable<List<T>> observable(final Query<T> query) {
return Observable.create(new ObservableOnSubscribe<List<T>>() {
@Override
public void subscribe(final ObservableEmitter<List<T>> emitter) throws Exception {
final DataSubscription dataSubscription = query.subscribe().observer(new DataObserver<List<T>>() {
@Override
public void onData(List<T> data) {
if (!emitter.isDisposed()) {
emitter.onNext(data);
}
}
});
emitter.setCancellable(new Cancellable() {
@Override
public void cancel() throws Exception {
dataSubscription.cancel();
}
});
}
});
}
示例8: downloadRemoteArchive
import io.reactivex.Observable; //导入依赖的package包/类
public static Observable<Event> downloadRemoteArchive(final FileSystem fs, final RemoteArchive remoteArchive, final Path targetDirectory) {
Preconditions.checkNotNull(fs);
Preconditions.checkNotNull(remoteArchive);
Preconditions.checkNotNull(targetDirectory);
final Path zipFilePath = targetDirectory.getParent().resolve(targetDirectory.getFileName() + ".zip");
return Observable.concat(
// Download the file
CommonTasks.downloadRemoteFile(fs, remoteArchive.asRemoteFile(), zipFilePath),
// Unpack the zip
MoreCompletables.fromRunnable(() -> {
EvenMoreFiles.unzip(
zipFilePath,
targetDirectory,
remoteArchive.subPath,
StandardCopyOption.REPLACE_EXISTING);
}).toObservable()).subscribeOn(Schedulers.io());
}
示例9: enqueue
import io.reactivex.Observable; //导入依赖的package包/类
public void enqueue(final ModuleCallback<T> callback) {
synchronized (this) {
if (mExecuted) {
throw new IllegalStateException("每个ModuleCall只能enqueue一次");
}
mExecuted = true;
}
if (mCanceled || mDone) {
return;
}
mModuleCallback = callback;
if (mObservable instanceof Observable) {
subscribeObservable((Observable<T>) mObservable);
} else if (mObservable instanceof Single) {
subscribeSingle((Single<T>) mObservable);
} else if (mObservable instanceof Flowable) {
subscribeFlowable((Flowable<T>) mObservable);
} else {
subscribeMaybe((Maybe<T>) mObservable);
}
}
示例10: onCreate
import io.reactivex.Observable; //导入依赖的package包/类
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoginObservable = Observable
.timer(TIME_DELAY, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.map(aLong -> "User id is " + UUID.randomUUID().toString());
mLoginFlowable = Flowable
.timer(TIME_DELAY, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.map(aLong -> "User id is " + UUID.randomUUID().toString());
mCompositeDisposable = new CompositeDisposable();
findViewById(R.id.button_observable).setOnClickListener(this);
findViewById(R.id.button_flowable).setOnClickListener(this);
}
示例11: onCustomCall
import io.reactivex.Observable; //导入依赖的package包/类
/**
* 使用EasyHttp调用自定义api 注意:如果有签名的注意路径有"/"的情况如下
* https://www.xxx.com/v1/account/login (正确)
* https://www.xxx.com//v1/account/login (错误 可能会导致签名失败)
*/
public void onCustomCall(View view) {
final String name = "18688994275";
final String pass = "123456";
final CustomRequest request = EasyHttp.custom().addConverterFactory(GsonConverterFactory.create(new Gson()))
.sign(true)
.timeStamp(true)
.params(ComParamContact.Login.ACCOUNT, name)
.params(ComParamContact.Login.PASSWORD, MD5.encrypt4login(pass, AppConstant.APP_SECRET))
.build();
LoginService mLoginService = request.create(LoginService.class);
Observable<ApiResult<AuthModel>> observable = request.call(mLoginService.login("v1/account/login", request.getParams().urlParamsMap));
Disposable disposable = observable.subscribe(new Consumer<ApiResult<AuthModel>>() {
@Override
public void accept(@NonNull ApiResult<AuthModel> result) throws Exception {
showToast(result.toString());
}
}, new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
showToast(throwable.getMessage());
}
});
//EasyHttp.cancelSubscription(disposable);//取消订阅
}
示例12: getAllClients
import io.reactivex.Observable; //导入依赖的package包/类
public static Observable<List<Client>> getAllClients() {
ClientsService service = ServiceGenerator.createService(ClientsService.class);
return service.getAllClients(UrlManager.getAllClientsURL())
.flatMap(new Function<JsonElement, Observable<List<Client>>>() {
@Override
public Observable<List<Client>> apply(JsonElement jsonElement) throws Exception {
if(jsonElement != null) {
Log.i("Get All Clients" , "JSON: "+jsonElement.toString());
if(jsonElement.isJsonArray()) {
List<Client> clients = Client.ClientsListParser.fromJsonArray(jsonElement.getAsJsonArray());
return Observable.just(clients);
} else {
return Observable.error(new Exception("Expected a JSON Array"));
}
} else {
return Observable.just((List<Client>) new ArrayList<Client>());
}
}
}).observeOn(AndroidSchedulers.mainThread());
}
示例13: viewsAreCalledBeforeLifecycleIsReadyWithoutLifecycleAwareRx
import io.reactivex.Observable; //导入依赖的package包/类
@Test
public void viewsAreCalledBeforeLifecycleIsReadyWithoutLifecycleAwareRx() throws Exception {
// Lifecycle is "active" once it is STARTED, it's not ready yet at INITIALIZED or CREATED.
lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Observable.interval(1, TimeUnit.MILLISECONDS)
.subscribeWith(new DisposableObserver<Long>() {
@Override
public void onNext(final Long value) {
LifecycleTest.this.methodOnViewCalled = true;
}
@Override
public void onError(final Throwable e) {
}
@Override
public void onComplete() {
}
});
// Need to wait to give it time to potentially fail
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(true, methodOnViewCalled);
}
示例14: getWhatsNewIcons
import io.reactivex.Observable; //导入依赖的package包/类
public Disposable getWhatsNewIcons() {
return Observable.fromArray(mView.getResources().getStringArray(R.array.whatsnew))
.map(new Function<String, IconBean>() {
@Override
public IconBean apply(@NonNull String s) throws Exception {
IconBean bean = new IconBean();
bean.id = mView.getResources().getIdentifier(s, "drawable", BuildConfig.APPLICATION_ID);
bean.name = s;
return bean;
}
}).toList().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<IconBean>>() {
@Override
public void accept(List<IconBean> list) throws Exception {
mView.onLoadData(list);
}
});
}
示例15: startWithTest
import io.reactivex.Observable; //导入依赖的package包/类
@Test
public void startWithTest() throws Exception {
Observable.fromArray(nums)
.startWith(-1)
.test()
.assertValueCount(7)
.assertValueAt(0, -1);
//也可以这样
Observable.fromArray(nums)
.startWith(Observable.just(-1))
.test()
.assertValueCount(7)
.assertValueAt(0, -1);
}