当前位置: 首页>>代码示例>>Java>>正文


Java Observable类代码示例

本文整理汇总了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);
}
 
开发者ID:KnowledgeBegger,项目名称:MyEyepetizer,代码行数:18,代码来源:SearchActivity.java

示例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;
}
 
开发者ID:TryGhost,项目名称:Ghost-Android,代码行数:17,代码来源:AuthService.java

示例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));
}
 
开发者ID:PacktPublishing,项目名称:Learning-RxJava,代码行数:18,代码来源:Ch4_3.java

示例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);
  }
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:20,代码来源:ProductDetailsPresenter.java

示例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;
	});

}
 
开发者ID:PacktPublishing,项目名称:Reactive-Programming-With-Java-9,代码行数:19,代码来源:Modern_Testing.java

示例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);
}
 
开发者ID:PacktPublishing,项目名称:Reactive-Programming-With-Java-9,代码行数:23,代码来源:Modern_Testing.java

示例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();
                }
            });
        }
    });
}
 
开发者ID:greenrobot,项目名称:ObjectBoxRxJava,代码行数:26,代码来源:RxQuery.java

示例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());
    }
 
开发者ID:LoopPerfect,项目名称:buckaroo,代码行数:23,代码来源:CommonTasks.java

示例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);
    }
}
 
开发者ID:linyongsheng,项目名称:android-arch-mvvm,代码行数:23,代码来源:ModuleCall.java

示例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);
}
 
开发者ID:tranngoclam,项目名称:rx-progress-dialog,代码行数:18,代码来源:MainActivity.java

示例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);//取消订阅
}
 
开发者ID:zhou-you,项目名称:RxEasyHttp,代码行数:31,代码来源:MainActivity.java

示例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());
}
 
开发者ID:ayounes3333,项目名称:GSB-2017-Android,代码行数:21,代码来源:ClientsNetworkCalls.java

示例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);
}
 
开发者ID:WaylonBrown,项目名称:LifecycleAwareRx,代码行数:26,代码来源:LifecycleTest.java

示例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);
                }
            });
}
 
开发者ID:iAcn,项目名称:MBEStyle,代码行数:21,代码来源:IconShowPresenter.java

示例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);
}
 
开发者ID:qingmei2,项目名称:RxFamilyUsage-Android,代码行数:15,代码来源:RxJava2CombineTest.java


注:本文中的io.reactivex.Observable类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。