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


Java Maybe类代码示例

本文整理汇总了Java中io.reactivex.Maybe的典型用法代码示例。如果您正苦于以下问题:Java Maybe类的具体用法?Java Maybe怎么用?Java Maybe使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Maybe类属于io.reactivex包,在下文中一共展示了Maybe类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import io.reactivex.Maybe; //导入依赖的package包/类
public static void main(String[] args) {
	// TODO Auto-generated method stub

	Maybe<List<String>> month_maybe = Maybe.create(emitter -> {
		try {
			String[] monthArray = { "Jan", "Feb", "Mar", "Apl", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov",
					"Dec" };

			List<String> months = Arrays.asList(monthArray);
			if (months != null && !months.isEmpty()) {
				emitter.onSuccess(months);
			} else {
				emitter.onComplete();
			}
		} catch (Exception e) {
			emitter.onError(e);
		}
	});
	month_maybe.subscribe(s->System.out.println(s));
	
}
 
开发者ID:PacktPublishing,项目名称:Reactive-Programming-With-Java-9,代码行数:22,代码来源:DemoMaybe.java

示例2: download

import io.reactivex.Maybe; //导入依赖的package包/类
@Override
public Maybe<Response> download(final Request request) {

    return Maybe.create(new MaybeOnSubscribe<CloseableHttpResponse>(){

        @Override
        public void subscribe(MaybeEmitter emitter) throws Exception {

            emitter.onSuccess(httpManager.getResponse(request));
        }
    }).map(new Function<CloseableHttpResponse, Response>() {

        @Override
        public Response apply(CloseableHttpResponse closeableHttpResponse) throws Exception {

            String html = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
            Response response = new Response();
            response.setContent(html);
            response.setStatusCode(closeableHttpResponse.getStatusLine().getStatusCode());
            return response;
        }
    });
}
 
开发者ID:fengzhizi715,项目名称:NetDiscovery,代码行数:24,代码来源:HttpClientDownloader.java

示例3: test

import io.reactivex.Maybe; //导入依赖的package包/类
@Test public void test() {

        MaybeSubject<String> subject = MaybeSubject.create();
        Maybe<String> maybeSource = subject.hide();


        TestObserver testObserver = new TestObserver();
        CompositeDisposable composite = new CompositeDisposable();
        Disposable disposable = maybeSource
                .compose(DisposableAttach.<String>to(composite))
                .subscribeWith(testObserver);

        subject.onSuccess("Foo");
        testObserver.assertValue("Foo");
        assertTrue(composite.size() == 1);
        composite.dispose();
        assertTrue(composite.size() == 0);
        assertTrue(composite.isDisposed());
        assertTrue(disposable.isDisposed());
        assertTrue(testObserver.isDisposed());
    }
 
开发者ID:cp949,项目名称:DisposableAttach,代码行数:22,代码来源:DisposableAttachMaybeTest.java

示例4: findKeyPairFor

import io.reactivex.Maybe; //导入依赖的package包/类
@Override
public Maybe<AesKeyPair> findKeyPairFor(int accountId, long sessionId) {
    return Maybe.create(e -> {
        List<AesKeyPair> pairs = mData.get(accountId);
        AesKeyPair result = null;
        if (Objects.nonNull(pairs)) {
            for (AesKeyPair pair : pairs) {
                if (pair.getSessionId() == sessionId) {
                    result = pair;
                    break;
                }
            }
        }

        if (Objects.nonNull(result)) {
            e.onSuccess(result);
        }

        e.onComplete();
    });
}
 
开发者ID:PhoenixDevTeam,项目名称:Phoenix-for-VK,代码行数:22,代码来源:KeysRamStore.java

示例5: testMaybeToSingleEmpty

import io.reactivex.Maybe; //导入依赖的package包/类
@Test
public void testMaybeToSingleEmpty() {
    final List<Object> results = new LinkedList<>();

    singleOrException(Maybe.empty(), HttpStatus.SC_BAD_REQUEST, "Too few elements")
            .subscribe((ignore) -> fail(), (e) -> results.add(e));

    assertEquals(1, results.size());

    Object result = results.get(0);

    if (result.getClass() != ServiceException.class) {
        fail();
    }

    ServiceException serviceException = (ServiceException) result;

    assertEquals(HttpStatus.SC_BAD_REQUEST, serviceException.getStatusCode());
    assertEquals("Too few elements", serviceException.getMessage());
}
 
开发者ID:Atypon-OpenSource,项目名称:wayf-cloud,代码行数:21,代码来源:FacadePoliciesTest.java

示例6: enqueue

import io.reactivex.Maybe; //导入依赖的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

示例7: download

import io.reactivex.Maybe; //导入依赖的package包/类
@Override
public Maybe<Response> download(Request request) {

    okhttp3.Request okrequest = new okhttp3.Request.Builder()
            .url(request.getUrl())
            .build();

    return Maybe.create(new MaybeOnSubscribe<okhttp3.Response>(){

        @Override
        public void subscribe(MaybeEmitter emitter) throws Exception {

            emitter.onSuccess(client.newCall(okrequest).execute());
        }
    }).map(new Function<okhttp3.Response, Response>() {

        @Override
        public Response apply(okhttp3.Response resp) throws Exception {

            String html = resp.body().string();
            Response response = new Response();
            response.setContent(html);
            response.setStatusCode(resp.code());
            return response;
        }
    });
}
 
开发者ID:fengzhizi715,项目名称:NetDiscovery,代码行数:28,代码来源:OkHttpDownloader.java

示例8: getElement

import io.reactivex.Maybe; //导入依赖的package包/类
public static <T extends RealmObject> Maybe<T> getElement(final Function<Realm, T> query) {
    return Maybe.create(emitter -> {
        final Realm realm = Realm.getDefaultInstance();
        final T result = query.apply(realm);
        if (result != null && result.isLoaded() && result.isValid()) {
            emitter.onSuccess(realm.copyFromRealm(result));
        } else {
            emitter.onComplete();
        }
        emitter.setCancellable(realm::close);
    });
}
 
开发者ID:Popalay,项目名称:RxRealm,代码行数:13,代码来源:RxRealm.java

示例9: loadLastForecastOnComplete

import io.reactivex.Maybe; //导入依赖的package包/类
@Test
public void loadLastForecastOnComplete() {
    when(lastForecastStore.get()).thenReturn(Maybe.<Channel>empty());

    presenter.loadLastForecast();
    verify(view).showContent();
}
 
开发者ID:tobyhs,项目名称:WeatherWeight,代码行数:8,代码来源:ForecastPresenterTest.java

示例10: getFile

import io.reactivex.Maybe; //导入依赖的package包/类
/**
 * Asynchronously downloads the object at this {@link StorageReference} to a specified system filepath.
 *
 * @param storageRef     represents a reference to a Google Cloud Storage object.
 * @param destinationUri a file system URI representing the path the object should be downloaded to.
 * @return a {@link Maybe} which emits an {@link FileDownloadTask.TaskSnapshot} if success.
 */
@NonNull
public static Maybe<FileDownloadTask.TaskSnapshot> getFile(@NonNull final StorageReference storageRef,
                                                           @NonNull final Uri destinationUri) {
    return Maybe.create(new MaybeOnSubscribe<FileDownloadTask.TaskSnapshot>() {
        @Override
        public void subscribe(MaybeEmitter<FileDownloadTask.TaskSnapshot> emitter) throws Exception {
            RxHandler.assignOnTask(emitter, storageRef.getFile(destinationUri));
        }
    });
}
 
开发者ID:DVT,项目名称:showcase-android,代码行数:18,代码来源:RxFirebaseStorage.java

示例11: viewsAreOnlyCalledWhenLifecycleActiveWithMaybe

import io.reactivex.Maybe; //导入依赖的package包/类
@Test
public void viewsAreOnlyCalledWhenLifecycleActiveWithMaybe() throws Exception {
	Maybe.just("test")
		.compose(LifecycleBinder.bind(lifecycleOwner, new DisposableMaybeObserver<String>() {
			@Override
			public void onSuccess(final String 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(false, methodOnViewCalled);

	lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
	TimeUnit.MILLISECONDS.sleep(100);
	assertEquals(false, methodOnViewCalled);

	lifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START);
	TimeUnit.MILLISECONDS.sleep(100);
	// At this point the views should now be called since the lifecycle is active
	assertEquals(true, methodOnViewCalled);
}
 
开发者ID:WaylonBrown,项目名称:LifecycleAwareRx,代码行数:32,代码来源:LifecycleTest.java

示例12: read

import io.reactivex.Maybe; //导入依赖的package包/类
@Override
public Maybe<IdentityProvider> read(Long id) {
    IdentityProviderQuery query = new IdentityProviderQuery().setId(id);

    return Single.just(query)
            .compose((single) -> DaoPolicies.applySingle(single))
            .flatMapMaybe((_query) -> dbExecutor.executeSelectFirst(readSql, _query, resultClass));
}
 
开发者ID:Atypon-OpenSource,项目名称:wayf-cloud,代码行数:9,代码来源:IdentityProviderDaoDbImpl.java

示例13: observeMultipleSingleValueEvent

import io.reactivex.Maybe; //导入依赖的package包/类
/**
 * Method which retrieve a list of DataSnapshot from multiple {@link DatabaseReference}.
 *
 * @param whereRefs array of {@link DatabaseReference references.}
 * @return a {@link Flowable} which emmit {@link DataSnapshot} from the given queries.
 */
@NonNull
public static Flowable<DataSnapshot> observeMultipleSingleValueEvent(@NonNull DatabaseReference... whereRefs) {
   @SuppressWarnings("unchecked")
   Maybe<DataSnapshot>[] singleQueries = (Maybe<DataSnapshot>[]) Array.newInstance(Maybe.class, whereRefs.length);
   for (int i = 0; i < whereRefs.length; i++) {
      singleQueries[i] = (observeSingleValueEvent(whereRefs[i]));
   }
   return Maybe.mergeArray(singleQueries);
}
 
开发者ID:DVT,项目名称:showcase-android,代码行数:16,代码来源:RxFirebaseDatabase.java

示例14: updateMetadata

import io.reactivex.Maybe; //导入依赖的package包/类
/**
 * Asynchronously uploads a stream of data to this {@link StorageReference}.
 *
 * @param storageRef represents a reference to a Google Cloud Storage object.
 * @param metadata   {@link StorageMetadata} containing additional information (MIME type, etc.) about the object being uploaded.
 * @return a {@link Maybe} which emits an {@link StorageMetadata} if success.
 */
@NonNull
public static Maybe<StorageMetadata> updateMetadata(@NonNull final StorageReference storageRef,
                                                    @NonNull final StorageMetadata metadata) {
    return Maybe.create(new MaybeOnSubscribe<StorageMetadata>() {
        @Override
        public void subscribe(MaybeEmitter<StorageMetadata> emitter) throws Exception {
            RxHandler.assignOnTask(emitter, storageRef.updateMetadata(metadata));
        }
    });
}
 
开发者ID:DVT,项目名称:showcase-android,代码行数:18,代码来源:RxFirebaseStorage.java

示例15: bind_whenSubscribingWithWorkerLifecycle_shouldMapToWorkerStartEvent

import io.reactivex.Maybe; //导入依赖的package包/类
@Test
public void bind_whenSubscribingWithWorkerLifecycle_shouldMapToWorkerStartEvent() {
  BehaviorRelay<InteractorEvent> lifecycle = BehaviorRelay.createDefault(InteractorEvent.ACTIVE);
  bind(lifecycle, worker);
  verify(worker).onStart(argumentCaptor.capture());

  Maybe observable = argumentCaptor.getValue().requestScope();
  WorkerEventCallback callback = new WorkerEventCallback();
  observable.subscribe(callback);
  lifecycle.accept(InteractorEvent.ACTIVE);
  assertThat(callback.getWorkerEvent()).isEqualTo(WorkerEvent.START);
}
 
开发者ID:uber,项目名称:RIBs,代码行数:13,代码来源:WorkerBinderTest.java


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