當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。