Java 类io.reactivex.functions.Predicate 实例源码

项目:AndroidSensors    文件:BasicSensorRequirementCheckerTest.java   
@Test
public void isRequired_IMULocationWifiAndBluetooth_areRequired() throws Exception {
    HashSet<SensorType> sensorTypes = new HashSet<>();
    sensorTypes.addAll(Arrays.asList(SensorType.imuValues()));
    sensorTypes.add(SensorType.LOCATION);
    sensorTypes.addAll(Arrays.asList(SensorType.wifiValues()));
    sensorTypes.addAll(Arrays.asList(SensorType.bluetoothValues()));

    Long count = Observable.fromIterable(sensorTypes)
            .map(new Function<SensorType, Boolean>() {
                @Override
                public Boolean apply(SensorType sensorType) throws Exception {
                    return basicSensorRequirementChecker.isRequired(sensorType);
                }
            }).filter(new Predicate<Boolean>() {
                @Override
                public boolean test(Boolean required) throws Exception {
                    return required;
                }
            }).count()
            .blockingGet();

    assertThat(count.intValue(), equalTo(sensorTypes.size()));
}
项目:RxDiffUtil    文件:DiffRequestManagerRoboTest.java   
@Test
public void single_ReturnsSharedSingle() {
    // Given
    final DiffRequest spyRequest = spy(mDiffRequest);

    // When
    final Single<RxDiffResult> single = DiffRequestManager.single(spyRequest);

    // Then
    for (int i = 0; i < 5; ++i) {
        final TestObserver<RxDiffResult> testObserver = new TestObserver<>();

        single.subscribe(testObserver);

        testObserver.awaitTerminalEvent(500, TimeUnit.MILLISECONDS);
        testObserver.assertValue(new Predicate<RxDiffResult>() {
            @Override
            public boolean test(@NonNull RxDiffResult rxDiffResult) throws Exception {
                return rxDiffResult.getTag().equals(TEST_TAG);
            }
        });
    }

    then(spyRequest).should(times(1)).isDetectingMoves();
}
项目:RxFirebase2    文件:RxFirebaseStorageTest.java   
@SuppressWarnings("Duplicates") @Test public void testGetFile() {
  mockSuccessfulResultForTask(mockFileDownloadTask, mockFileDownloadTaskSnapshot);
  when(mockStorageReference.getFile(mockFile)).thenReturn(mockFileDownloadTask);
  when(mockFileDownloadTaskSnapshot.getBytesTransferred()).thenReturn(1000L);
  when(mockFileDownloadTaskSnapshot.getTotalByteCount()).thenReturn(1000L);

  TestObserver<FileDownloadTask.TaskSnapshot> obs = TestObserver.create();

  RxFirebaseStorage.getFile(mockStorageReference, mockFile).subscribe(obs);

  verifyAddOnCompleteListenerForTask(mockFileDownloadTask);

  callOnComplete(mockFileDownloadTask);
  obs.dispose();

  callOnComplete(mockFileDownloadTask);

  obs.assertNoErrors();
  obs.assertComplete();
  obs.assertValue(new Predicate<FileDownloadTask.TaskSnapshot>() {
    @Override public boolean test(FileDownloadTask.TaskSnapshot taskSnapshot) throws Exception {
      return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount()
          && taskSnapshot.getTotalByteCount() == 1000;
    }
  });
}
项目:RxFirebase2    文件:RxFirebaseStorageTest.java   
@Test public void testGetMetadata() {
  mockSuccessfulResultForTask(mockStorageMetadataTask, mockStorageMetadata);
  when(mockStorageReference.getMetadata()).thenReturn(mockStorageMetadataTask);
  when(mockStorageMetadata.getName()).thenReturn("Test");

  TestObserver<StorageMetadata> obs = TestObserver.create();

  RxFirebaseStorage.getMetadata(mockStorageReference).subscribe(obs);

  verifyAddOnCompleteListenerForTask(mockStorageMetadataTask);

  callOnComplete(mockStorageMetadataTask);
  obs.dispose();

  callOnComplete(mockStorageMetadataTask);

  obs.assertNoErrors();
  obs.assertComplete();
  obs.assertValue(new Predicate<StorageMetadata>() {
    @Override public boolean test(StorageMetadata storageMetadata) throws Exception {
      return "Test".equals(storageMetadata.getName());
    }
  });
}
项目:Rx_java2_soussidev    文件:RxBus_java.java   
public <CLASS> Observable<Getter<CLASS>> onGet(final Class<CLASS> theClass) {
    return onEvent(AskedEvent.class)//I wait for an event (askevent) of CLASS
            .filter(new Predicate<AskedEvent>() {
                @Override
                public boolean test(@NonNull AskedEvent askedEvent) throws Exception {
                    return askedEvent.askedObject.equals(theClass);
                }
            })
            .map(new Function<AskedEvent, Getter<CLASS>>() {
                @Override
                public Getter<CLASS> apply(@NonNull AskedEvent o) throws Exception {
                    return new Getter<CLASS>() {
                        //then I send to the listener a Getter (interface)
                        //when the getter is notified, the value is sent to the first subscrier
                        //who called the method `get`
                        @Override
                        public void get(CLASS value) {
                            post(value); //the value is published on the bus
                        }
                    };
                }
            });
}
项目:XSnow    文件:FirstRemoteStrategy.java   
@Override
public <T> Observable<CacheResult<T>> execute(ApiCache apiCache, String cacheKey, Observable<T> source, Type type) {
    Observable<CacheResult<T>> remote = loadRemote(apiCache, cacheKey, source);
    remote.onErrorReturn(new Function<Throwable, CacheResult<T>>() {
        @Override
        public CacheResult<T> apply(Throwable throwable) throws Exception {
            return null;
        }
    });
    Observable<CacheResult<T>> cache = loadCache(apiCache, cacheKey, type);
    return Observable.concatDelayError(Arrays.asList(remote,cache)).filter(new Predicate<CacheResult<T>>() {
        @Override
        public boolean test(CacheResult<T> tCacheResult) throws Exception {
            return tCacheResult != null && tCacheResult.getCacheData() != null;
        }
    }).firstElement().toObservable();
}
项目:RxFirebase2    文件:RxFirebaseStorageTest.java   
@Test public void testUpdateMetadata() {
  when(mockStorageMetadata.getName()).thenReturn("metadata");
  mockSuccessfulResultForTask(mockStorageMetadataTask, mockStorageMetadata);

  TestObserver<StorageMetadata> obs = TestObserver.create();
  when(mockStorageReference.updateMetadata(mockStorageMetadata)).thenReturn(
      mockStorageMetadataTask);

  RxFirebaseStorage.updateMetadata(mockStorageReference, mockStorageMetadata).subscribe(obs);

  verifyAddOnCompleteListenerForTask(mockStorageMetadataTask);

  callOnComplete(mockStorageMetadataTask);
  obs.dispose();

  callOnComplete(mockStorageMetadataTask);

  obs.assertNoErrors();
  obs.assertComplete();
  obs.assertValue(new Predicate<StorageMetadata>() {
    @Override public boolean test(StorageMetadata metadata) throws Exception {
      return "metadata".equals(metadata.getName());
    }
  });
}
项目:NullAway    文件:NullAwayRxSupportNegativeCases.java   
private Observable<Integer> filterWithIfThenMapNullableContainer(
    Observable<NullableContainer<String>> observable) {
  return observable
      .filter(
          new Predicate<NullableContainer<String>>() {
            @Override
            public boolean test(NullableContainer<String> container) throws Exception {
              if (container.get() != null) {
                return true;
              } else {
                return false;
              }
            }
          })
      .map(
          new Function<NullableContainer<String>, Integer>() {
            @Override
            public Integer apply(NullableContainer<String> c) throws Exception {
              return c.get().length();
            }
          });
}
项目:SuperHttp    文件:FirstRemoteStrategy.java   
@Override
public <T> Observable<CacheResult<T>> execute(ApiCache apiCache, String cacheKey, Observable<T> source, Type type) {
    Observable<CacheResult<T>> cache = loadCache(apiCache, cacheKey, type);
    cache.onErrorReturn(new Function<Throwable, CacheResult<T>>() {
        @Override
        public CacheResult<T> apply(Throwable throwable) throws Exception {
            return null;
        }
    });
    Observable<CacheResult<T>> remote = loadRemote(apiCache, cacheKey, source);
    return Observable.concat(remote, cache).filter(new Predicate<CacheResult<T>>() {
        @Override
        public boolean test(CacheResult<T> tCacheResult) throws Exception {
            return tCacheResult != null && tCacheResult.getCacheData() != null;
        }
    }).firstElement().toObservable();
}
项目:NullAway    文件:NullAwayRxSupportNegativeCases.java   
private Observable<NullableContainer<String>> filterThenDistinctUntilChanged(
    Observable<NullableContainer<String>> observable) {
  return observable
      .filter(
          new Predicate<NullableContainer<String>>() {
            @Override
            public boolean test(NullableContainer<String> container) throws Exception {
              return container.get() != null;
            }
          })
      .distinctUntilChanged(
          new BiPredicate<NullableContainer<String>, NullableContainer<String>>() {
            @Override
            public boolean test(NullableContainer<String> nc1, NullableContainer<String> nc2) {
              return nc1.get().length() == nc2.get().length()
                  && nc1.get().contains(nc2.get())
                  && nc2.get().contains(nc1.get());
            }
          });
}
项目:NullAway    文件:NullAwayRxSupportNegativeCases.java   
private Maybe<Integer> testMaybe(Maybe<NullableContainer<String>> maybe) {
  return maybe
      .filter(
          new Predicate<NullableContainer<String>>() {
            @Override
            public boolean test(NullableContainer<String> container) throws Exception {
              return container.get() != null;
            }
          })
      .map(
          new Function<NullableContainer<String>, Integer>() {
            @Override
            public Integer apply(NullableContainer<String> c) throws Exception {
              return c.get().length();
            }
          });
}
项目:NullAway    文件:NullAwayRxSupportNegativeCases.java   
private Maybe<Integer> testSingle(Single<NullableContainer<String>> single) {
  return single
      .filter(
          new Predicate<NullableContainer<String>>() {
            @Override
            public boolean test(NullableContainer<String> container) throws Exception {
              return container.get() != null;
            }
          })
      .map(
          new Function<NullableContainer<String>, Integer>() {
            @Override
            public Integer apply(NullableContainer<String> c) throws Exception {
              return c.get().length();
            }
          });
}
项目:NullAway    文件:NullAwayRxSupportPositiveCases.java   
private Observable<Integer> filterWithIfThenMapNullableContainerNullableOnSomeBranch(
    Observable<NullableContainer<String>> observable) {
  return observable
      .filter(
          new Predicate<NullableContainer<String>>() {
            @Override
            public boolean test(NullableContainer<String> container) throws Exception {
              if (container.get() != null) {
                return true;
              } else {
                return perhaps();
              }
            }
          })
      .map(
          new Function<NullableContainer<String>, Integer>() {
            @Override
            public Integer apply(NullableContainer<String> c) throws Exception {
              // BUG: Diagnostic contains: dereferenced expression
              return c.get().length();
            }
          });
}
项目:NullAway    文件:NullAwayRxSupportPositiveCases.java   
private Observable<Integer> filterWithIfThenMapNullableContainerNullableOnSomeBranchAnyOrder(
    Observable<NullableContainer<String>> observable) {
  return observable
      .filter(
          new Predicate<NullableContainer<String>>() {
            @Override
            public boolean test(NullableContainer<String> container) throws Exception {
              if (container.get() == null) {
                return perhaps();
              } else {
                return true;
              }
            }
          })
      .map(
          new Function<NullableContainer<String>, Integer>() {
            @Override
            public Integer apply(NullableContainer<String> c1) throws Exception {
              // BUG: Diagnostic contains: dereferenced expression
              return c1.get().length();
            }
          });
}
项目:MyEyepetizer    文件:DailyActivity.java   
private void setRecyclerViewScrollListener() {
    LoadMoreDelegate delegate = new LoadMoreDelegate(new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean isLoading() {
            return mIsLoading;
        }

        @Override
        public void onLoadMore() {
            Observable<IssueDataBean> observable = mDailyApi.loadMoreDailyItem(mNextPageUrl);
            mIsLoading = true;
            observable
                    .filter(new Predicate<IssueDataBean>() {
                        @Override
                        public boolean test(@NonNull IssueDataBean issueDataBean) throws Exception {
                            return issueDataBean != null;
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(mObserver);
        }
    });
    delegate.attach(mRecyclerView);
}
项目:RxFirebase2    文件:RxFirebaseStorageTest.java   
@Test public void testGetBytes() {
  mockSuccessfulResultForTask(mockBytesTask, new byte[] { 1, 2, 3 });
  Mockito.when(mockStorageReference.getBytes(3)).thenReturn(mockBytesTask);

  TestObserver<byte[]> obs = TestObserver.create();

  RxFirebaseStorage.getBytes(mockStorageReference, 3).subscribe(obs);
  verifyAddOnCompleteListenerForTask(mockBytesTask);

  callOnComplete(mockBytesTask);
  obs.dispose();

  callOnComplete(mockBytesTask);

  obs.assertNoErrors();
  obs.assertComplete();
  obs.assertValue(new Predicate<byte[]>() {
    @Override public boolean test(byte[] bytes) throws Exception {
      return Arrays.equals(bytes, new byte[] { 1, 2, 3 });
    }
  });
}
项目:RIBs    文件:RibActivityTest.java   
@Test
public void rxActivity_shouldCallback_onLowMemory() {
  ActivityController<EmptyActivity> activityController = buildActivity(EmptyActivity.class);
  RibActivity activity = activityController.setup().get();
  TestObserver<ActivityCallbackEvent> testSub = new TestObserver<>();
  activity
      .callbacks()
      .filter(
          new Predicate<ActivityCallbackEvent>() {
            @Override
            public boolean test(ActivityCallbackEvent activityEvent) throws Exception {
              return activityEvent.getType() == ActivityCallbackEvent.Type.LOW_MEMORY;
            }
          })
      .subscribe(testSub);

  activity.onLowMemory();

  testSub.assertValue(ActivityCallbackEvent.create(ActivityCallbackEvent.Type.LOW_MEMORY));
}
项目:MyEyepetizer    文件:SearchActivity.java   
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);
}
项目:RxNetwork    文件:RxNetworkInfoPredicate.java   
/**
 * Determines if any of specified transport types occurred.
 *
 * @param transportTypes one or many {@code NetworkCapabilities#TRANSPORT_*}
 *
 * @return {@code true} if any of the given transport types occurred, {@code false} otherwise
 */
public static Predicate<RxNetworkInfo> hasTransportType(final int... transportTypes) {
  return new Predicate<RxNetworkInfo>() {
    @Override
    public boolean test(RxNetworkInfo networkInfo) throws Exception {
      final NetworkCapabilities networkCapabilities = networkInfo.getNetworkCapabilities();

      if (networkCapabilities != null) {
        for (Integer transportType : transportTypes) {
          if (networkCapabilities.hasTransport(transportType)) {
            return true;
          }
        }
      }

      return false;
    }
  };
}
项目:flowr    文件:FragmentResultPublisherImpl.java   
public Disposable observeResultsForFragment(final String fragmentId, Consumer<ResultResponse> consumer) {
    return publishSubject
            .filter(new Predicate<ResultResponse>() {
                @Override
                public boolean test(ResultResponse resultResponse) throws Exception {
                    return resultResponse.fragmentId.equals(fragmentId);
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(consumer, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    throwable.printStackTrace();
                }
            });
}
项目:RxFirebase2    文件:RxFirebaseStorageTest.java   
@Test public void testPutStream() {
  mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot);
  when(mockStorageReference.putStream(mockInputStream)).thenReturn(mockUploadTask);
  when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L);
  when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L);

  TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create();

  RxFirebaseStorage.putStream(mockStorageReference, mockInputStream).subscribe(obs);

  verifyAddOnCompleteListenerForTask(mockUploadTask);

  callOnComplete(mockUploadTask);
  obs.dispose();

  callOnComplete(mockUploadTask);

  obs.assertNoErrors();
  obs.assertComplete();
  obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() {
    @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception {
      return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount()
          && taskSnapshot.getTotalByteCount() == 1000L;
    }
  });
}
项目:J-Chain    文件:ConditionTest.java   
@Test
public void thenToItemWithValidConditionThenReturnAnOptionalContainingItem() {

    TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration)
            .when(new Predicate<TestClass>() {
                @Override
                public boolean test(TestClass testClass) throws Exception {
                    return true;
                }
            })
            .thenTo(new TestClassTwo("1"))
            .defaultIfEmpty(new TestClassTwo("2"))
            .call();

    assertEquals("1", result.text);


}
项目:J-Chain    文件:ConditionTest.java   
@Test
public void thenToItemWithInvalidConditionThenReturnAnOptionalContainingNull() {

    TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration)
            .when(new Predicate<TestClass>() {
                @Override
                public boolean test(TestClass testClass) throws Exception {
                    return false;
                }
            })
            .thenTo(new TestClassTwo("1"))
            .defaultIfEmpty(new TestClassTwo("2"))
            .call();

    assertEquals("2", result.text);


}
项目:RxFirebase2    文件:RxFirebaseDatabaseTest.java   
@Test public void testDataChangesOfClazz() {
  TestObserver<Optional<String>> sub = TestObserver.create();

  RxFirebaseDatabase.dataChangesOf(mockDatabaseReference, String.class).subscribe(sub);

  verifyAddValueEventListener();
  callValueEventOnDataChange("Foo");

  sub.assertNotComplete();
  sub.assertValueCount(1);
  sub.assertValue(new Predicate<Optional<String>>() {
    @Override public boolean test(Optional<String> stringOptional) throws Exception {
      return stringOptional.isPresent() && "Foo".equals(stringOptional.get());
    }
  });

  sub.dispose();

  callValueEventOnDataChange("Foo");

  // Ensure no more values are emitted after unsubscribe
  sub.assertValueCount(1);
}
项目:J-Chain    文件:ConditionTest.java   
@Test
public void thenToCallableWithInvalidConditionThenReturnAnOptionalContainingNull() {

    TestClassTwo result = new Chain<>(new TestClass(), chainConfiguration)
            .when(new Predicate<TestClass>() {
                @Override
                public boolean test(TestClass testClass) throws Exception {
                    return false;
                }
            })
            .thenTo(new Callable<TestClassTwo>() {

                @Override
                public TestClassTwo call() throws Exception {
                    return new TestClassTwo("1");
                }
            })
            .defaultIfEmpty(new TestClassTwo("2"))
            .call();

    assertEquals("2", result.text);


}
项目:J-Chain    文件:ConditionTest.java   
@Test(expected = UnsupportedOperationException.class)
public void thenToCallableWithExceptionThenThrowException() {
    new Chain<>(new TestClass(), chainConfiguration)
            .when(new Predicate<TestClass>() {
                @Override
                public boolean test(TestClass testClass) throws Exception {
                    return true;
                }
            })
            .thenTo(new Callable<TestClassTwo>() {

                @Override
                public TestClassTwo call() throws Exception {
                    throw new UnsupportedOperationException();
                }
            });

}
项目:InstantAppSample    文件:TripRepository.java   
public Maybe<Trip> getTrip(final String tripId) {
    return getTrips()
            .toObservable()
            .flatMap(new Function<List<Trip>, ObservableSource<? extends Trip>>() {
                @Override
                public ObservableSource<? extends Trip> apply(List<Trip> tripList) throws Exception {
                    return Observable.fromIterable(tripList);
                }
            })
            .filter(new Predicate<Trip>() {
                @Override
                public boolean test(Trip trip) throws Exception {
                    return trip.getId().equals(tripId);
                }
            })
            .singleElement();
}
项目:sqlbrite-sqlcipher    文件:BriteDatabase.java   
/**
 * See {@link #createQuery(String, String, String...)} for usage. This overload allows for
 * monitoring multiple tables for changes.
 *
 * @see SQLiteDatabase#rawQuery(String, String[])
 */
@CheckResult @NonNull
public QueryObservable createQuery(@NonNull final Iterable<String> tables, @NonNull String sql,
    @NonNull String... args) {
  Predicate<Set<String>> tableFilter = new Predicate<Set<String>>() {
    @Override public boolean test(Set<String> triggers) {
      for (String table : tables) {
        if (triggers.contains(table)) {
          return true;
        }
      }
      return false;
    }

    @Override public String toString() {
      return tables.toString();
    }
  };
  return createQuery(tableFilter, sql, args);
}
项目:AndroidSensors    文件:BasicSensorConfigTest.java   
@Test
public void getBackpressureStrategy_forAllSensors_returnsBufferStrategy() throws Exception {
    HashSet<SensorType> allSensors = new HashSet<>(Arrays.asList(SensorType.values()));

    Long count = Observable.fromIterable(allSensors)
            .map(new Function<SensorType, BackpressureStrategy>() {
                @Override
                public BackpressureStrategy apply(SensorType sensorType) throws Exception {
                    return basicSensorConfig.getBackpressureStrategy(sensorType);
                }
            })
            .filter(new Predicate<BackpressureStrategy>() {
                @Override
                public boolean test(BackpressureStrategy backpressureStrategy) throws Exception {
                    return backpressureStrategy.equals(BackpressureStrategy.BUFFER);
                }
            })
            .count()
            .blockingGet();

    assertThat(count.intValue(), equalTo(allSensors.size()));
}
项目:rebase-android    文件:RxFilters.java   
/**
 * Just for the Collections.
 *
 * @param <T> The input.
 * @return true if the input collection is not empty.
 * @throws ClassCastException If the input is not an instance of Collection.
 */
public static <T> Predicate<T> notEmpty() {
    return new Predicate<T>() {
        @Override
        public boolean test(@NonNull T t) throws Exception {
            return !((Collection) t).isEmpty();
        }
    };
}
项目:rebase-android    文件:RxFilters.java   
public static <T> Predicate<T> notNull() {
    return new Predicate<T>() {
        @Override
        public boolean test(@NonNull T t) {
            return t != null;
        }
    };
}
项目:store2realm    文件:PostService.java   
@Override
public Flowable<Optional<List<Post>>> getAll(Filter filter, final SortingMode sortingMode) {

    // this IF case is here only to demonstrate the usage of filtering and sorting mode in the UI
    // this logic should be on the server side and not here !
    // !!!! The filter and the sort are hardcoded here (to match presenter choices).
    if(sortingMode != null && filter != null){
        final int userIdAllowed = (int) filter.entrySet().iterator().next().getValue().value;

        // special return for demo
        return wrapOptional(apiService.getPosts()
                .flatMapIterable(new Function<List<Post>, Iterable<Post>>() {
                    @Override
                    public Iterable<Post> apply(List<Post> posts) throws Exception {
                        Collections.sort(posts, new Comparator<Post>() {
                            @Override
                            public int compare(Post p0, Post p1) {
                                return p0.userId - p1.userId; // hardcoded ordering by userId
                            }
                        });
                        return posts;
                    }
                })
                .filter(new Predicate<Post>() {
                    @Override
                    public boolean test(Post post) throws Exception {
                        return post.userId == userIdAllowed;
                    }
                })
                .toList()
                .toFlowable()
        );
    }

    // you can wrap the retrofit response directly in a
    // Optional object by default for more convenience
    return wrapOptional(apiService.getPosts());
}
项目:GitHub    文件:FilterExampleActivity.java   
private void doSomeWork() {
    Observable.just(1, 2, 3, 4, 5, 6)
            .filter(new Predicate<Integer>() {
                @Override
                public boolean test(Integer integer) throws Exception {
                    return integer % 2 == 0;
                }
            })
            .subscribe(getObserver());
}
项目:GitHub    文件:MainPresenter.java   
@Override
public void checkVersion(final String currentVersion) {
    addSubscribe(mRetrofitHelper.fetchVersionInfo()
            .compose(RxUtil.<MyHttpResponse<VersionBean>>rxSchedulerHelper())
            .compose(RxUtil.<VersionBean>handleMyResult())
            .filter(new Predicate<VersionBean>() {
                @Override
                public boolean test(@NonNull VersionBean versionBean) throws Exception {
                    return Integer.valueOf(currentVersion.replace(".", "")) < Integer.valueOf(versionBean.getCode().replace(".", ""));
                }
            })
            .map(new Function<VersionBean, String>() {
                @Override
                public String apply(VersionBean bean) {
                    StringBuilder content = new StringBuilder("版本号: v");
                    content.append(bean.getCode());
                    content.append("\r\n");
                    content.append("版本大小: ");
                    content.append(bean.getSize());
                    content.append("\r\n");
                    content.append("更新内容:\r\n");
                    content.append(bean.getDes().replace("\\r\\n","\r\n"));
                    return content.toString();
                }
            })
            .subscribeWith(new CommonSubscriber<String>(mView) {
                @Override
                public void onNext(String s) {
                    mView.showUpdateDialog(s);
                }
            })
    );
}
项目:GitHub    文件:MainPresenter.java   
@Override
public void checkVersion(final String currentVersion) {
    addSubscribe(mDataManager.fetchVersionInfo()
            .compose(RxUtil.<MyHttpResponse<VersionBean>>rxSchedulerHelper())
            .compose(RxUtil.<VersionBean>handleMyResult())
            .filter(new Predicate<VersionBean>() {
                @Override
                public boolean test(@NonNull VersionBean versionBean) throws Exception {
                    return Integer.valueOf(currentVersion.replace(".", "")) < Integer.valueOf(versionBean.getCode().replace(".", ""));
                }
            })
            .map(new Function<VersionBean, String>() {
                @Override
                public String apply(VersionBean bean) {
                    StringBuilder content = new StringBuilder("版本号: v");
                    content.append(bean.getCode());
                    content.append("\r\n");
                    content.append("版本大小: ");
                    content.append(bean.getSize());
                    content.append("\r\n");
                    content.append("更新内容:\r\n");
                    content.append(bean.getDes().replace("\\r\\n","\r\n"));
                    return content.toString();
                }
            })
            .subscribeWith(new CommonSubscriber<String>(mView) {
                @Override
                public void onNext(String s) {
                    mView.showUpdateDialog(s);
                }
            })
    );
}
项目:Weather-Guru-MVP    文件:ManageCityActivity.java   
@Override protected void init() {
  setSupportActionBar(toolbar);
  showBackButton(true);
  setTitle(getString(R.string.screen_manage_cities));

  recyclerCities.setLayoutManager(new LinearLayoutManager(this));
  adapter = new CityAdapter(this);
  recyclerCities.setAdapter(adapter);

  autocompleteTxtCity.setAdapter(autoCompleteAdapter);
  autocompleteTxtCity.setOnItemClickListener(this);

  Observable<String> observable = RxTextView.textChangeEvents(autocompleteTxtCity)
      .skip(2)
      .debounce(500, TimeUnit.MILLISECONDS)
      .map(new Function<TextViewTextChangeEvent, String>() {
        @Override public String apply(TextViewTextChangeEvent textViewTextChangeEvent)
            throws Exception {
          return textViewTextChangeEvent.text().toString();
        }
      })
      .filter(new Predicate<String>() {
        @Override public boolean test(String s) throws Exception {
          return s.length() > 2;
        }
      });

  presenter.loadAutocompleteCities(observable);
  presenter.loadCities();
}
项目:RxFirebase2    文件:RxFirebaseStorageTest.java   
@Test public void testPutStreamWithMetadata() {
  mockSuccessfulResultForTask(mockUploadTask, mockUploadTaskSnapshot);
  when(mockStorageReference.putStream(mockInputStream, mockStorageMetadata)).thenReturn(
      mockUploadTask);
  when(mockUploadTaskSnapshot.getBytesTransferred()).thenReturn(1000L);
  when(mockUploadTaskSnapshot.getTotalByteCount()).thenReturn(1000L);

  TestObserver<UploadTask.TaskSnapshot> obs = TestObserver.create();

  RxFirebaseStorage.putStream(mockStorageReference, mockInputStream, mockStorageMetadata)
      .subscribe(obs);

  verifyAddOnCompleteListenerForTask(mockUploadTask);

  callOnComplete(mockUploadTask);
  obs.dispose();

  callOnComplete(mockUploadTask);

  obs.assertNoErrors();
  obs.assertComplete();
  obs.assertValue(new Predicate<UploadTask.TaskSnapshot>() {
    @Override public boolean test(UploadTask.TaskSnapshot taskSnapshot) throws Exception {
      return taskSnapshot.getBytesTransferred() == taskSnapshot.getTotalByteCount()
          && taskSnapshot.getTotalByteCount() == 1000L;
    }
  });
}
项目:Rx_java2_soussidev    文件:ConnectivityPredicate.java   
/**
 * Filter, which returns true if at least one given type occurred
 *
 * @param types int, which can have one or more types
 * @return true if at least one given type occurred
 */
public static Predicate<Connectivity> hasType(final int... types) {
    final int[] extendedTypes = appendUnknownNetworkTypeToTypes(types);
    return new Predicate<Connectivity>() {
        @Override public boolean test(@NonNull Connectivity connectivity) throws Exception {
            for (int type : extendedTypes) {
                if (connectivity.getType() == type) {
                    return true;
                }
            }
            return false;
        }
    };
}