androidx.arch.core.util.Function Java Examples

The following examples show how to use androidx.arch.core.util.Function. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransformationsTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoRedispatchSwitchMap() {
    LiveData<Integer> trigger = new MutableLiveData<>();
    final LiveData<String> first = new MutableLiveData<>();
    LiveData<String> result = Transformations.switchMap(trigger,
            new Function<Integer, LiveData<String>>() {
                @Override
                public LiveData<String> apply(Integer input) {
                    return first;
                }
            });

    Observer<String> observer = mock(Observer.class);
    result.observe(mOwner, observer);
    verify(observer, never()).onChanged(anyString());
    first.setValue("first");
    trigger.setValue(1);
    verify(observer).onChanged("first");
    reset(observer);
    trigger.setValue(2);
    verify(observer, never()).onChanged(anyString());
}
 
Example #2
Source File: TransformationsTest.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Test
public void noObsoleteValueTest() {
    MutableLiveData<Integer> numbers = new MutableLiveData<>();
    LiveData<Integer> squared = Transformations.map(numbers, new Function<Integer, Integer>() {
        @Override
        public Integer apply(Integer input) {
            return input * input;
        }
    });

    Observer observer = mock(Observer.class);
    squared.setValue(1);
    squared.observeForever(observer);
    verify(observer).onChanged(1);
    squared.removeObserver(observer);
    reset(observer);
    numbers.setValue(2);
    squared.observeForever(observer);
    verify(observer, only()).onChanged(4);
}
 
Example #3
Source File: QueryRepository.java    From lttrs-android with Apache License 2.0 6 votes vote down vote up
public LiveData<PagedList<ThreadOverviewItem>> getThreadOverviewItems(final EmailQuery query) {
    return Transformations.switchMap(databaseLiveData, new Function<LttrsDatabase, LiveData<PagedList<ThreadOverviewItem>>>() {
        @Override
        public LiveData<PagedList<ThreadOverviewItem>> apply(LttrsDatabase database) {
            return new LivePagedListBuilder<>(database.queryDao().getThreadOverviewItems(query.toQueryString()), 30)
                    .setBoundaryCallback(new PagedList.BoundaryCallback<ThreadOverviewItem>() {
                        @Override
                        public void onZeroItemsLoaded() {
                            Log.d("lttrs", "onZeroItemsLoaded");
                            requestNextPage(query, null); //conceptually in terms of loading indicators this is more of a page request
                            super.onZeroItemsLoaded();
                        }

                        @Override
                        public void onItemAtEndLoaded(@NonNull ThreadOverviewItem itemAtEnd) {
                            Log.d("lttrs", "onItemAtEndLoaded(" + itemAtEnd.emailId + ")");
                            requestNextPage(query, itemAtEnd.emailId);
                            super.onItemAtEndLoaded(itemAtEnd);
                        }
                    })
                    .build();
        }
    });
}
 
Example #4
Source File: FlexibleViewModel.java    From FlexibleAdapter with Apache License 2.0 6 votes vote down vote up
public FlexibleViewModel() {
    identifier = new MutableLiveData<>();
    liveItems = Transformations.switchMap(identifier, new Function<Identifier, LiveData<List<AdapterItem>>>() {
        @Override
        public LiveData<List<AdapterItem>> apply(Identifier input) {
            return Transformations.map(getSource(input), new Function<Source, List<AdapterItem>>() {
                @Override
                public List<AdapterItem> apply(Source source) {
                    if (isSourceValid(source)) {
                        return map(source);
                    } else {
                        return liveItems.getValue();
                    }
                }
            });
        }
    });
}
 
Example #5
Source File: DataSource.java    From kripton with Apache License 2.0 5 votes vote down vote up
@NonNull
static <X, Y> Function<List<X>, List<Y>> createListFunction(
        final @NonNull Function<X, Y> innerFunc) {
    return new Function<List<X>, List<Y>>() {
        @Override
        public List<Y> apply(@NonNull List<X> source) {
            List<Y> out = new ArrayList<>(source.size());
            for (int i = 0; i < source.size(); i++) {
                out.add(innerFunc.apply(source.get(i)));
            }
            return out;
        }
    };
}
 
Example #6
Source File: DataSource.java    From kripton with Apache License 2.0 5 votes vote down vote up
static <A, B> List<B> convert(Function<List<A>, List<B>> function, List<A> source) {
    List<B> dest = function.apply(source);
    if (dest.size() != source.size()) {
        throw new IllegalStateException("Invalid Function " + function
                + " changed return size. This is not supported.");
    }
    return dest;
}
 
Example #7
Source File: PositionalDataSource.java    From kripton with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <ToValue> DataSource<Integer, ToValue> map(
        @NonNull Function<Value, ToValue> function) {
    throw new UnsupportedOperationException(
            "Inaccessible inner type doesn't support map op");
}
 
Example #8
Source File: PositionalDataSource.java    From kripton with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <ToValue> DataSource<Integer, ToValue> mapByPage(
        @NonNull Function<List<Value>, List<ToValue>> function) {
    throw new UnsupportedOperationException(
            "Inaccessible inner type doesn't support map op");
}
 
Example #9
Source File: PositionalDataSource.java    From kripton with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <ToValue> DataSource<Integer, ToValue> mapByPage(
        @NonNull Function<List<Value>, List<ToValue>> function) {
    throw new UnsupportedOperationException(
            "Inaccessible inner type doesn't support map op");
}
 
Example #10
Source File: PositionalDataSource.java    From kripton with Apache License 2.0 5 votes vote down vote up
@NonNull
@Override
public <ToValue> DataSource<Integer, ToValue> map(
        @NonNull Function<Value, ToValue> function) {
    throw new UnsupportedOperationException(
            "Inaccessible inner type doesn't support map op");
}
 
Example #11
Source File: DataSource.java    From kripton with Apache License 2.0 5 votes vote down vote up
static <A, B> List<B> convert(Function<List<A>, List<B>> function, List<A> source) {
    List<B> dest = function.apply(source);
    if (dest.size() != source.size()) {
        throw new IllegalStateException("Invalid Function " + function
                + " changed return size. This is not supported.");
    }
    return dest;
}
 
Example #12
Source File: DataSource.java    From kripton with Apache License 2.0 5 votes vote down vote up
@NonNull
static <X, Y> Function<List<X>, List<Y>> createListFunction(
        final @NonNull Function<X, Y> innerFunc) {
    return new Function<List<X>, List<Y>>() {
        @Override
        public List<Y> apply(@NonNull List<X> source) {
            List<Y> out = new ArrayList<>(source.size());
            for (int i = 0; i < source.size(); i++) {
                out.add(innerFunc.apply(source.get(i)));
            }
            return out;
        }
    };
}
 
Example #13
Source File: BrapiExportActivity.java    From Field-Book with GNU General Public License v2.0 5 votes vote down vote up
private void putObservations() {

        brAPIService.putObservations(observationsNeedingSync,
                BrAPIService.getBrapiToken(this),
                new Function<List<NewObservationDbIdsObservations>, Void>() {
                    @Override
                    public Void apply(final List<NewObservationDbIdsObservations> observationDbIds) {

                        (BrapiExportActivity.this).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                processPutObservationsResponse(observationDbIds);
                                observationsComplete = true;
                                uploadComplete();
                            }
                        });
                        return null;
                    }
                }, new Function<Integer, Void>() {

                    @Override
                    public Void apply(final Integer code) {

                        (BrapiExportActivity.this).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                putObservationsError = processErrorCode(code);
                                observationsComplete = true;
                                uploadComplete();
                            }
                        });

                        return null;
                    }
                }
        );
    }
 
Example #14
Source File: MoviesRemoteDataSource.java    From PopularMovies with MIT License 5 votes vote down vote up
/**
 * Load movies for certain filter.
 */
public RepoMoviesResult loadMoviesFilteredBy(MoviesFilterType sortBy) {
    MovieDataSourceFactory sourceFactory =
            new MovieDataSourceFactory(mMovieService, mExecutors.networkIO(), sortBy);

    // paging configuration
    PagedList.Config config = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(PAGE_SIZE)
            .build();

    // Get the paged list
    LiveData<PagedList<Movie>> moviesPagedList = new LivePagedListBuilder<>(sourceFactory, config)
            .setFetchExecutor(mExecutors.networkIO())
            .build();

    LiveData<Resource> networkState = Transformations.switchMap(sourceFactory.sourceLiveData, new Function<MoviePageKeyedDataSource, LiveData<Resource>>() {
        @Override
        public LiveData<Resource> apply(MoviePageKeyedDataSource input) {
            return input.networkState;
        }
    });

    // Get pagedList and network errors exposed to the viewmodel
    return new RepoMoviesResult(
            moviesPagedList,
            networkState,
            sourceFactory.sourceLiveData
    );
}
 
Example #15
Source File: TestObserver.java    From livedata-testing with Apache License 2.0 5 votes vote down vote up
/**
 * Allows assertion of some mapped value extracted from originally observed values.
 * History of observed values is retained.
 * <p>
 * This can became useful when you want to perform assertions on some complex structure and
 * you want to assert only on one field.
 *
 * @param mapper Function to map originally observed value.
 * @param <N>    Type of mapper.
 * @return TestObserver for mapped value
 */
public <N> TestObserver<N> map(Function<T, N> mapper) {
  TestObserver<N> newObserver = create();
  // We want the history match the current one
  for (T value : valueHistory) {
    newObserver.onChanged(mapper.apply(value));
  }

  doOnChanged(new Map<>(newObserver, mapper));

  return newObserver;
}
 
Example #16
Source File: TestObserver.java    From livedata-testing with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that this TestObserver did not receive any value for which
 * the provided predicate returns true.
 *
 * @param valuePredicate the predicate that receives the observed values
 *                       and should return true for the value not supposed to be received.
 * @return this
 */
public TestObserver<T> assertNever(Function<T, Boolean> valuePredicate) {
  int size = valueHistory.size();
  for (int valueIndex = 0; valueIndex < size; valueIndex++) {
    T value = this.valueHistory.get(valueIndex);
    if (valuePredicate.apply(value)) {
      throw fail("Value at position " + valueIndex + " matches predicate "
        + valuePredicate.toString() + ", which was not expected.");
    }
  }

  return this;
}
 
Example #17
Source File: TestObserver.java    From livedata-testing with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that for this TestObserver last received value
 * the provided predicate returns true.
 *
 * @param valuePredicate the predicate that receives the observed value
 *                       and should return true for the expected value.
 * @return this
 */
public TestObserver<T> assertValue(@NonNull Function<T, Boolean> valuePredicate) {
  T value = value();

  if (!valuePredicate.apply(value)) {
    throw fail("Value " + valueAndClass(value) + " does not match the predicate "
      + valuePredicate.toString() + ".");
  }

  return this;
}
 
Example #18
Source File: BrapiExportActivity.java    From Field-Book with GNU General Public License v2.0 5 votes vote down vote up
private void putImageContent(final com.fieldbook.tracker.brapi.Image image, final List<com.fieldbook.tracker.brapi.Image> uploads) {

        brAPIService.putImageContent(image, BrAPIService.getBrapiToken(this),
                new Function<Image, Void>() {
                    @Override
                    public Void apply(final Image responseImage) {

                        (BrapiExportActivity.this).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String fieldBookId = image.getFieldBookDbId();
                                processPutImageContentResponse(responseImage, fieldBookId);
                                putImageContentUpdatesCount++;
                                uploadComplete();
                            }
                        });
                        return null;
                    }
                }, new Function<Integer, Void>() {

                    @Override
                    public Void apply(final Integer code) {

                        (BrapiExportActivity.this).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                putImageContentError = processErrorCode(code);
                                putImageContentUpdatesCount++;
                                uploadComplete();
                            }
                        });

                        return null;
                    }
                }
        );
    }
 
Example #19
Source File: VideosViewModel.java    From tv-samples with Apache License 2.0 5 votes vote down vote up
@Inject
public VideosViewModel(Application application, VideosRepository repository) {
    super(application);

    mRepository = repository;

    mAllCategories = mRepository.getAllCategories();

    mSearchResults = Transformations.switchMap(
            mQuery, new Function<String, LiveData<List<VideoEntity>>>() {
                @Override
                public LiveData<List<VideoEntity>> apply(final String queryMessage) {
                    return mRepository.getSearchResult(queryMessage);
                }
            });


    mVideoById = Transformations.switchMap(
            mVideoId, new Function<Long, LiveData<VideoEntity>>() {
                @Override
                public LiveData<VideoEntity> apply(final Long videoId) {
                    return mRepository.getVideoById(videoId);
                }
            });

    /**
     * Using switch map function to react to the change of observed variable, the benefits of
     * this mapping method is we don't have to re-create the live data every time.
     */
    mAllVideosByCategory = Transformations.switchMap(mVideoCategory, new Function<String, LiveData<List<VideoEntity>>>() {
        @Override
        public LiveData<List<VideoEntity>> apply(String category) {
            return mRepository.getVideosInSameCategoryLiveData(category);
        }
    });
}
 
Example #20
Source File: TransformationsTest.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwitchMapToNull() {
    LiveData<Integer> trigger = new MutableLiveData<>();
    final LiveData<String> first = new MutableLiveData<>();
    LiveData<String> result = Transformations.switchMap(trigger,
            new Function<Integer, LiveData<String>>() {
                @Override
                public LiveData<String> apply(Integer input) {
                    if (input == 1) {
                        return first;
                    } else {
                        return null;
                    }
                }
            });

    Observer<String> observer = mock(Observer.class);
    result.observe(mOwner, observer);
    verify(observer, never()).onChanged(anyString());
    first.setValue("first");
    trigger.setValue(1);
    verify(observer).onChanged("first");
    reset(observer);

    trigger.setValue(2);
    verify(observer, never()).onChanged(anyString());
    assertThat(first.hasObservers(), is(false));
}
 
Example #21
Source File: TransformationsTest.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwitchMap2() {
    LiveData<Integer> trigger = new MutableLiveData<>();
    final LiveData<String> first = new MutableLiveData<>();
    final LiveData<String> second = new MutableLiveData<>();
    LiveData<String> result = Transformations.switchMap(trigger,
            new Function<Integer, LiveData<String>>() {
                @Override
                public LiveData<String> apply(Integer input) {
                    if (input == 1) {
                        return first;
                    } else {
                        return second;
                    }
                }
            });

    Observer<String> observer = mock(Observer.class);
    result.observe(mOwner, observer);

    verify(observer, never()).onChanged(anyString());
    trigger.setValue(1);
    verify(observer, never()).onChanged(anyString());
    first.setValue("fi");
    verify(observer).onChanged("fi");
    first.setValue("rst");
    verify(observer).onChanged("rst");

    second.setValue("second");
    reset(observer);
    verify(observer, never()).onChanged(anyString());
    trigger.setValue(2);
    verify(observer).onChanged("second");
    reset(observer);
    first.setValue("failure");
    verify(observer, never()).onChanged(anyString());
}
 
Example #22
Source File: TransformationsTest.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Test
public void testMap() {
    LiveData<String> source = new MutableLiveData<>();
    LiveData<Integer> mapped = Transformations.map(source, new Function<String, Integer>() {
        @Override
        public Integer apply(String input) {
            return input.length();
        }
    });
    Observer<Integer> observer = mock(Observer.class);
    mapped.observe(mOwner, observer);
    source.setValue("four");
    verify(observer).onChanged(4);
}
 
Example #23
Source File: TransformationsTest.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwitchMap() {
    LiveData<Integer> trigger = new MutableLiveData<>();
    final LiveData<String> first = new MutableLiveData<>();
    final LiveData<String> second = new MutableLiveData<>();
    LiveData<String> result = Transformations.switchMap(trigger,
            new Function<Integer, LiveData<String>>() {
                @Override
                public LiveData<String> apply(Integer input) {
                    if (input == 1) {
                        return first;
                    } else {
                        return second;
                    }
                }
            });

    Observer<String> observer = mock(Observer.class);
    result.observe(mOwner, observer);
    verify(observer, never()).onChanged(anyString());
    first.setValue("first");
    trigger.setValue(1);
    verify(observer).onChanged("first");
    second.setValue("second");
    reset(observer);
    verify(observer, never()).onChanged(anyString());
    trigger.setValue(2);
    verify(observer).onChanged("second");
    reset(observer);
    first.setValue("failure");
    verify(observer, never()).onChanged(anyString());
}
 
Example #24
Source File: BrapiServiceTest.java    From Field-Book with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void checkPostImageMetaData() {

    postImageMetaDataResponse = null;
    final CountDownLatch signal = new CountDownLatch(1);
    final String brapiToken = "Bearer YYYY";

    com.fieldbook.tracker.brapi.Image image = new com.fieldbook.tracker.brapi.Image("/path/test.jpg", missingImage);
    image.setUnitDbId("1");

    // Call our get study details endpoint with the same parsing that our classes use.
    this.brAPIService.postImageMetaData(image, brapiToken, new Function<Image, Void>() {
                @Override
                public Void apply(final Image response) {

                    postImageMetaDataResponse = response;
                    signal.countDown();

                    return null;
                }
            }, new Function<Integer, Void>() {

                @Override
                public Void apply(final Integer code) {

                    signal.countDown();

                    return null;
                }
            }
    );

    // Wait for our callback and evaluate how we did
    try {
        signal.await();

        assertTrue(postImageMetaDataResponse != null);

    } catch (InterruptedException e) {
        fail(e.toString());
    }
}
 
Example #25
Source File: BrapiServiceTest.java    From Field-Book with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void checkPutObservations() {

    putObservationsResponse = null;
    final CountDownLatch signal = new CountDownLatch(1);
    final String brapiToken = "Bearer YYYY";

    List<Observation> testObservations = new ArrayList<>();
    Observation testObservation = new Observation();
    testObservation.setCollector("Brapi Test");
    testObservation.setDbId("");
    testObservation.setTimestamp(OffsetDateTime.now());
    testObservation.setUnitDbId("1");
    testObservation.setVariableDbId("MO_123:100002");
    testObservation.setValue("5");
    testObservation.setStudyId("1001");
    testObservations.add(testObservation);

    // Call our get study details endpoint with the same parsing that our classes use.
    this.brAPIService.putObservations(testObservations, brapiToken, new Function<List<NewObservationDbIdsObservations>, Void>() {
                @Override
                public Void apply(final List<NewObservationDbIdsObservations> observationDbIds) {

                    putObservationsResponse = observationDbIds;
                    signal.countDown();

                    return null;
                }
            }, new Function<Integer, Void>() {

                @Override
                public Void apply(final Integer code) {

                    signal.countDown();

                    return null;
                }
            }
    );

    // Wait for our callback and evaluate how we did
    try {
        signal.await();

        assertTrue(putObservationsResponse != null);
        assertTrue(putObservationsResponse.size() == 1);
        assertTrue(putObservationsResponse.get(0).getObservationUnitDbId().equals("1"));
        assertTrue(putObservationsResponse.get(0).getObservationVariableDbId().equals("MO_123:100002"));

    } catch (InterruptedException e) {
        fail(e.toString());
    }
}
 
Example #26
Source File: WrapperPageKeyedDataSource.java    From kripton with Apache License 2.0 4 votes vote down vote up
WrapperPageKeyedDataSource(PageKeyedDataSource<K, A> source,
        Function<List<A>, List<B>> listFunction) {
    mSource = source;
    mListFunction = listFunction;
}
 
Example #27
Source File: PageKeyedDataSource.java    From kripton with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public final <ToValue> PageKeyedDataSource<Key, ToValue> mapByPage(
        @NonNull Function<List<Value>, List<ToValue>> function) {
    return new WrapperPageKeyedDataSource<>(this, function);
}
 
Example #28
Source File: PageKeyedDataSource.java    From kripton with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public final <ToValue> PageKeyedDataSource<Key, ToValue> map(
        @NonNull Function<Value, ToValue> function) {
    return mapByPage(createListFunction(function));
}
 
Example #29
Source File: WrapperItemKeyedDataSource.java    From kripton with Apache License 2.0 4 votes vote down vote up
WrapperItemKeyedDataSource(ItemKeyedDataSource<K, A> source,
        Function<List<A>, List<B>> listFunction) {
    mSource = source;
    mListFunction = listFunction;
}
 
Example #30
Source File: WrapperPositionalDataSource.java    From kripton with Apache License 2.0 4 votes vote down vote up
WrapperPositionalDataSource(PositionalDataSource<A> source,
        Function<List<A>, List<B>> listFunction) {
    mSource = source;
    mListFunction = listFunction;
}