Java 类android.arch.lifecycle.Transformations 实例源码

项目:Fairy    文件:GrepFilter.java   
@MainThread
static LiveData<LogcatContent> grepData(LiveData<LogcatContent> rawData, String grep) {
    return Transformations.map(rawData, logcatData -> {
        String content = logcatData.getContent();
        if (GREP_SIGNAL.equals(content)) {
            return logcatData;
        }


        if (content != null) {
            logcatData.setContent(parseHtml2(content,grep));
        }

        return logcatData;

    });
}
项目:android-persistence    文件:CustomResultViewModel.java   
private void subscribeToDbChanges() {
    LiveData<List<LoanWithUserAndBook>> loans
            = mDb.loanModel().findLoansByNameAfter("Mike", getYesterdayDate());

    // Instead of exposing the list of Loans, we can apply a transformation and expose Strings.
    mLoansResult = Transformations.map(loans,
            new Function<List<LoanWithUserAndBook>, String>() {
        @Override
        public String apply(List<LoanWithUserAndBook> loansWithUserAndBook) {
            StringBuilder sb = new StringBuilder();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm",
                    Locale.US);

            for (LoanWithUserAndBook loan : loansWithUserAndBook) {
                sb.append(String.format("%s\n  (Returned: %s)\n",
                        loan.bookTitle,
                        simpleDateFormat.format(loan.endTime)));
            }
            return sb.toString();
        }
    });
}
项目:android-persistence    文件:CustomResultViewModel.java   
private void subscribeToDbChanges() {
    // TODO: Modify this query to show only recent loans from specific user
    LiveData<List<LoanWithUserAndBook>> loans
            = mDb.loanModel().findAllWithUserAndBook();

    // Instead of exposing the list of Loans, we can apply a transformation and expose Strings.
    mLoansResult = Transformations.map(loans,
            new Function<List<LoanWithUserAndBook>, String>() {
        @Override
        public String apply(List<LoanWithUserAndBook> loansWithUserAndBook) {
            StringBuilder sb = new StringBuilder();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm",
                    Locale.US);

            for (LoanWithUserAndBook loan : loansWithUserAndBook) {
                sb.append(String.format("%s\n  (Returned: %s)\n",
                        loan.bookTitle,
                        simpleDateFormat.format(loan.endTime)));
            }
            return sb.toString();
        }
    });
}
项目:firebase-chat-android-architecture-components    文件:ConversationViewModel.java   
@Inject
public ConversationViewModel(InboxRepository repository) {
    this.conversationId = new MutableLiveData<>();

    conversation = Transformations.switchMap(conversationId, input -> {
        if (input.isEmpty()) {
            return AbsentLiveData.create();
        }
        return repository.conversation(input);
    });

    metaData = Transformations.switchMap(conversationId, input -> {
        if (input.isEmpty()) {
            return AbsentLiveData.create();
        }
        return repository.conversationMetaData(input);
    });
}
项目:android-architecture-components    文件:RepoViewModel.java   
@Inject
public RepoViewModel(RepoRepository repository) {
    this.repoId = new MutableLiveData<>();
    repo = Transformations.switchMap(repoId, input -> {
        if (input.isEmpty()) {
            return AbsentLiveData.create();
        }
        return repository.loadRepo(input.owner, input.name);
    });
    contributors = Transformations.switchMap(repoId, input -> {
        if (input.isEmpty()) {
            return AbsentLiveData.create();
        } else {
            return repository.loadContributors(input.owner, input.name);
        }

    });
}
项目:android-architecture-components    文件:UserViewModel.java   
@SuppressWarnings("unchecked")
@Inject
public UserViewModel(UserRepository userRepository, RepoRepository repoRepository) {
    user = Transformations.switchMap(login, login -> {
        if (login == null) {
            return AbsentLiveData.create();
        } else {
            return userRepository.loadUser(login);
        }
    });
    repositories = Transformations.switchMap(login, login -> {
        if (login == null) {
            return AbsentLiveData.create();
        } else {
            return repoRepository.loadRepos(login);
        }
    });
}
项目:foco    文件:DocListViewModel.java   
/**
 * Default constructor.
 * @param application
 */
public DocListViewModel(Application application) {
    super(application);

    // transform database created flag to live data.
    // if it is not created, it will return ABSENT field.
    // if it is created, it will return room live data.
    final DatabaseManager databaseManager = DatabaseManager.getInstance(application);
    LiveData<Boolean> databaseCreated = databaseManager.isDatabaseCreated();
    mObservableDocuments = Transformations.switchMap(databaseCreated,
            new Function<Boolean, LiveData<List<DocumentMetadata>>>() {
                @Override
                public LiveData<List<DocumentMetadata>> apply(Boolean isDbCreated) {
                    if (!Boolean.TRUE.equals(isDbCreated)) {
                        return ABSENT;
                    } else {
                        return databaseManager.getDatabase().documentDao().loadAllDocumentsMetadata();
                    }
                }
            });

    databaseManager.initDbAsync(this.getApplication());
}
项目:Daily    文件:PostsListViewModel.java   
PostsListViewModel(@NonNull Application application, String slug, int postCount, Retrofit retrofit) {
    super(application);
    mSlug = slug;
    mPostCount = postCount;
    mRetrofit = retrofit;

    mIsLoading.setValue(true);
    mOffset.setValue(0);

    // 当 mOffset 的值发生改变,就会执行 apply
    mListLiveData = Transformations.switchMap(mOffset, new Function<Integer, LiveData<List<PostsListBean>>>() {
        @Override
        public LiveData<List<PostsListBean>> apply(Integer input) {
            return handleData(input);
        }
    });
}
项目:mobile-buy-sdk-android    文件:ShippingRatesView.java   
public void bindViewModel(@NonNull final CheckoutShippingRatesViewModel viewModel) {
  if (this.viewModel != null) {
    throw new IllegalStateException("Already bound");
  }
  this.viewModel = viewModel;

  Transformations.map(viewModel.selectedShippingRateLiveData(), shippingRate ->
    shippingRate != null ? shippingRate.title : null)
    .observe(this, title -> {
      if (title != null) {
        shippingLineView.setText(title);
      } else {
        shippingLineView.setText(R.string.checkout_shipping_method_not_selected);
      }
    });

  Transformations.map(viewModel.selectedShippingRateLiveData(), shippingRate ->
    shippingRate != null ? CURRENCY_FORMAT.format(shippingRate.price)
      : getResources().getString(R.string.checkout_shipping_method_price_not_available))
    .observe(this, price -> priceView.setText(price));
}
项目:FlexibleAdapter    文件:FlexibleViewModel.java   
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();
                    }
                }
            });
        }
    });
}
项目:SampleAppArch    文件:RepoDao.java   
public LiveData<List<Repo>> loadOrdered(List<Integer> repoIds) {
  SparseIntArray order = new SparseIntArray();
  int index = 0;
  for (Integer repoId : repoIds) {
    order.put(repoId, index++);
  }
  return Transformations.map(loadById(repoIds), repositories -> {
    Collections.sort(repositories, (r1, r2) -> {
      int pos1 = order.get(r1.id);
      int pos2 = order.get(r2.id);
      return pos1 - pos2;
    });
    return repositories;
  });
}
项目:Repository-ArchComponents    文件:HeroViewModel.java   
public HeroViewModel() {
    this.heroRepository = HeroRepository.getInstance();
    this.heroResult = Transformations.switchMap(forceFetchHero, forceFetch -> {
        if (forceFetch == null) {
            return AbsentLiveData.create();
        }

        return heroRepository.getHero(forceFetch);
    });
}
项目:firestore-android-arch-components    文件:MainViewModel.java   
@Inject
MainViewModel(MainRepository repository) {
    this.repository = repository;
    filters.setValue(Filters.getDefault());
    isSignedIn = new LiveData<Boolean>() {
        @Override
        protected void onActive() {
            super.onActive();
            setValue(FirebaseAuth.getInstance().getCurrentUser() != null);
        }
    };

    restaurants = Transformations.switchMap(filters, repository::restaurants);
}
项目:android-architecture-components    文件:SearchViewModel.java   
@Inject
SearchViewModel(RepoRepository repoRepository) {
    nextPageHandler = new NextPageHandler(repoRepository);
    results = Transformations.switchMap(query, search -> {
        if (search == null || search.trim().length() == 0) {
            return AbsentLiveData.create();
        } else {
            return repoRepository.search(search);
        }
    });
}
项目:android-architecture-components    文件:RepoDao.java   
public LiveData<List<Repo>> loadOrdered(List<Integer> repoIds) {
    SparseIntArray order = new SparseIntArray();
    int index = 0;
    for (Integer repoId : repoIds) {
        order.put(repoId, index++);
    }
    return Transformations.map(loadById(repoIds), repositories -> {
        Collections.sort(repositories, (r1, r2) -> {
            int pos1 = order.get(r1.id);
            int pos2 = order.get(r2.id);
            return pos1 - pos2;
        });
        return repositories;
    });
}
项目:AndroidBlueprints    文件:UserViewModel.java   
@Inject
public UserViewModel(UserRepository userRepository) {
    this.repository = userRepository;
    if (user == null) {
        Timber.d("Init UserViewModel");
        userIdentifier = new MutableLiveData<>();
        user = Transformations.switchMap(userIdentifier, input -> {
            if (input == null) {
                return AbsentLiveData.create();
            }
            return repository.login(new LoginRequest(input.username, input.password));
        });
    }
}
项目:leanback-showcase    文件:VideosViewModel.java   
@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);
        }
    });
}
项目:mobile-buy-sdk-android    文件:CartHeaderView.java   
public void bindViewModel(final CartHeaderViewModel viewModel) {
  if (this.viewModel != null) {
    throw new IllegalStateException("Already bound");
  }
  this.viewModel = viewModel;

  Transformations.map(viewModel.cartTotalLiveData(), CURRENCY_FORMAT::format)
    .observe(this, (total) -> subtotalView.setText(total));

  viewModel.googleApiClientConnectionData().observe(this, connected ->
    androidPayCheckoutView.setVisibility(connected == Boolean.TRUE ? VISIBLE : GONE));
}
项目:FitnessHabits    文件:Param.java   
public LiveData<Type> liveData() {
    return Transformations.map(manager.paramRecordLiveData, record -> getValueOnRecord(record));
}
项目:FitnessHabits    文件:FieldInstance.java   
public LiveData<Type> liveData() {
    return Transformations.map(this.weightRepository.weightRecordLiveData, record -> field.getRecordValue(record));
}
项目:FitnessHabits    文件:MainActivityViewModel.java   
public void init(ParamRepository paramRepository) {
    this.paramRepository = paramRepository;
    date = Transformations.map(paramRepository.param().currentViewDate().liveData(),
            CalendarDate::getCalendardate);
}
项目:Fairy    文件:LogcatContentViewModel.java   
public LogcatContentViewModel(@NonNull Application application, LogcatContentRepository repository) {
    super(application);
    this.repository = repository;
    contentLiveData = Transformations.switchMap(isStartFirstLoad, isStart -> repository.getLogcatContent());
}
项目:Fairy    文件:ExampleUnitTest.java   
public void start() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 15; i++) {
                int finalI = i;
                if (i == 5) {
                    new Handler(Looper.getMainLooper()).post(() -> {
                        data.removeSource(rawData);
                        rawData.setValue("grep");
                        grepData = Transformations.map(rawData, str -> {
                            return str + " " + grep;
                        });

                        data.addSource(grepData, str -> {
                            data.setValue(str);
                        });
                    });
                    transData.postValue(true);
                    grep = " 222";
                }
                if (i == 6) {
                    new Handler(Looper.getMainLooper()).post(() -> {
                        data.removeSource(grepData);
                        rawData.setValue("raw");
                        data.addSource(rawData, str -> {
                            data.setValue(str);
                        });
                    });

                    transData.postValue(false);
                }
                if (i == 10) {
                    new Handler(Looper.getMainLooper()).post(() -> {
                        data.removeSource(rawData);
                        rawData.setValue("grep");
                        grepData = Transformations.map(rawData, str -> {
                            return str + " " + grep;
                        });

                        data.addSource(grepData, str -> {
                            data.setValue(str);
                        });
                    });
                    transData.postValue(true);
                    grep = " 333";
                }
                if (i != 5 && i != 6 && i != 10) {
                    rawData.postValue("sb: " + i);
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}
项目:Fairy    文件:ExampleUnitTest.java   
public LiveData<String> creat(String grep) {
    return Transformations.switchMap(transData, boo -> {
        return data;
    });
}
项目:AndroidNewArchitectureExample    文件:MainActivityViewModel.java   
@Inject
public MainActivityViewModel() {
    App.getComponent().inject(this);
    this.weatherInfoLiveData = Transformations.switchMap(cityNameLiveData, weatherRepository::getWeather);
}
项目:firestore-android-arch-components    文件:RatingViewModel.java   
@Inject
RatingViewModel(RestaurantRepository repository) {
    this.repository = repository;
    restaurant = Transformations.switchMap(id, repository::restaurant);
    ratings = Transformations.switchMap(id, repository::ratings);
}
项目:android-architecture-components    文件:RepoRepository.java   
public LiveData<Resource<List<Repo>>> search(String query) {
    return new NetworkBoundResource<List<Repo>, RepoSearchResponse>(appExecutors) {

        @Override
        protected void saveCallResult(@NonNull RepoSearchResponse item) {
            List<Integer> repoIds = item.getRepoIds();
            RepoSearchResult repoSearchResult = new RepoSearchResult(
                    query, repoIds, item.getTotal(), item.getNextPage());
            db.beginTransaction();
            try {
                repoDao.insertRepos(item.getItems());
                repoDao.insert(repoSearchResult);
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }

        @Override
        protected boolean shouldFetch(@Nullable List<Repo> data) {
            return data == null;
        }

        @NonNull
        @Override
        protected LiveData<List<Repo>> loadFromDb() {
            return Transformations.switchMap(repoDao.search(query), searchData -> {
                if (searchData == null) {
                    return AbsentLiveData.create();
                } else {
                    return repoDao.loadOrdered(searchData.repoIds);
                }
            });
        }

        @NonNull
        @Override
        protected LiveData<ApiResponse<RepoSearchResponse>> createCall() {
            return githubService.searchRepos(query);
        }

        @Override
        protected RepoSearchResponse processResponse(ApiResponse<RepoSearchResponse> response) {
            RepoSearchResponse body = response.body;
            if (body != null) {
                body.setNextPage(response.getNextPage());
            }
            return body;
        }
    }.asLiveData();
}
项目:mobile-buy-sdk-android    文件:RealCartViewModel.java   
@Override public LiveData<BigDecimal> cartTotalLiveData() {
  return Transformations.map(cartLiveData, cart -> cart != null ? cart.totalPrice() : BigDecimal.ZERO);
}