将向日葵应用程序ViewModel更改为仅显示植物列表?

时间:2019-05-05 18:18:27

标签: java android android-jetpack

我正在努力使用Google的向日葵应用程序作为我的应用程序的基础,如何从对变量“ growZoneNumber”的依赖中改变为仅返回所有植物?

这是从Google官方kotlin版本进行转换的人那里得到的Java代码:

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;
    }
}

谢谢。

1 个答案:

答案 0 :(得分:0)

花了一段时间让我找出答案,但是找到了答案(当然,里面的模型稍有不同

公共类PinViewModel扩展了ViewModel {

private PinRepository pinRepository;

PinViewModel(@NonNull PinRepository pinRepository) {
    this.pinRepository = pinRepository;
}

public LiveData<List<Pin>> getPins() {
    return pinRepository.getPins();
}

}