我正在尽力将Google的向日葵应用程序用于我的应用程序,如何从对变量" growzoneNumber"的依赖中改变,以便它只返回所有植物?<<<<<<<<
这是Java代码,因为它来自从Google官方Kotlin版本转换为Google的人:
package com.google.samples.apps.sunflower.viewmodels;
import com.google.samples.apps.sunflower.data.Plant;
import com.google.samples.apps.sunflower.data.PlantRepository;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
/**
* Created by Shawn Wang on 3/26/19.
*/
public class PlantListViewModel extends ViewModel {
private static final int NO_GROW_ZONE = -1;
private PlantRepository plantRepository;
private MutableLiveData<Integer> growZoneNumber;
public LiveData<List<Plant>> plants;
PlantListViewModel(@NonNull PlantRepository plantRepository) {
super();
this.plantRepository = plantRepository;
this.growZoneNumber = new MutableLiveData<>(-1);
this.plants = Transformations.switchMap(growZoneNumber, it -> {
if (it == NO_GROW_ZONE) {
return this.plantRepository.getPlants();
} else {
return this.plantRepository.getPlantsWIthGrowZoneNumber(it);
}
});
}
public void setGrowZoneNumber(int num) {
this.growZoneNumber.setValue(num);
}
public void cleanGrowZoneNumber() {
this.growZoneNumber.setValue(NO_GROW_ZONE);
}
public boolean isFiltered() {
return this.growZoneNumber.getValue() != NO_GROW_ZONE;
}
}
谢谢。
花了我一段时间来弄清楚,但找到了答案(当然在
内有略有不同的模型公共类PinViewModel扩展了ViewModel {
private PinRepository pinRepository;
PinViewModel(@NonNull PinRepository pinRepository) {
this.pinRepository = pinRepository;
}
public LiveData<List<Pin>> getPins() {
return pinRepository.getPins();
}
}