我怎样才能让一个ViewModel类回报倍数数据类型的活动或片段(How can I make on

2019-09-26 06:20发布

我在读这篇博客使用Android的架构组件与火力地堡实时数据库(第2部分)和我执行最后的代码片段,其工作。

private final FirebaseQueryLiveData liveData = new FirebaseQueryLiveData(HOT_STOCK_REF);
private final MediatorLiveData<HotStock> hotStockLiveData = new MediatorLiveData<>();

public HotStockViewModel() {
    // Set up the MediatorLiveData to convert DataSnapshot objects into HotStock objects
    hotStockLiveData.addSource(liveData, new Observer<DataSnapshot>() {
        @Override
        public void onChanged(@Nullable final DataSnapshot dataSnapshot) {
            if (dataSnapshot != null) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        hotStockLiveData.postValue(dataSnapshot.getValue(HotStock.class));
                    }
                }).start();
            } else {
                hotStockLiveData.setValue(null);
            }
        }
    });
}

实际上,我用它来返回包裹在LiveData HotStockViewModel对象的数组(通过结果从数据库中循环,我真的不知道我应该做的ViewModel类这个数据处理),并返回数组这只是显示它的片段。

是否有可能使用同样的ViewModel类只返回价格裹着LiveData数组(现在仍然还回到裹在LiveData的HotStockViewModel对象的数组)?

如果是,我怎么能做到这一点? 我不想通过它返回包裹在LiveData的HotStockViewModel对象的数组,然后循环,以获得价格片段。 我不想片段做任何数据操作可言,只显示数据。

我看到这个计算器的问题可以在Android架构组件视图模型从多个LiveData返回模型组成的对象? 但我不明白的答案。 我仍然是一个Java初学者。

Answer 1:

我真的不知道我是否应该在ViewModel类做这个数据操作

在Android的MVVM模式,我认为你正在使用,这是不可取的在ViewModel类进行数据操作。 而是创建一个回购类应对此进行处理。 视图模型类应该只得到数据从回购类,然后把它传递给哪个UI组件需要它。



Answer 2:

是否有可能使用同样的ViewModel类只返回价格裹着LiveData数组(现在仍然还回到裹在LiveData的HotStockViewModel对象的数组)

你可以创建一个像例如一个数据类

 public class ResponseData {
            private ArrayList<HotStock> hotstockVm;
            private ArrayList<double> prices;

            public ArrayList<double> getPrices(){
              return prices;
            };

            public void setPrices(ArrayList<double>prices ){
              this.prices = prices;
            };
    }

然后创建一个回购类

    public class Repo{

    private final FirebaseQueryLiveData liveData = new FirebaseQueryLiveData(HOT_STOCK_REF);
    private final MediatorLiveData hotStockLiveData = new MediatorLiveData();
    private ResponseData response = new ResponseData();
    private ArrayList<HotStock> hotstock = new ArrayList<>();
    private ArrayList<Double> prices = new ArrayList<>();


    public LiveData<ResponseData> getData() {
        //a mutableLivedata to hold data got
        final MutableLivedata<ResponseData> dataMutableLiveData = new MutableLivedata<>();
        // Set up the MediatorLiveData to convert DataSnapshot objects into HotStock objects
        hotStockLiveData.addSource(liveData, new Observer() {
            @Override
            public void onChanged(@Nullable final DataSnapshot dataSnapshot) {
                if (dataSnapshot != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            hotStockLiveData.postValue(dataSnapshot.getValue(HotStock.class));
                            //get each hotstock object from firebase
                            HotStock object = dataSnapshot.getValue(HotStock.class);
                            //get the price from each hotstock object
                            //if class HotStock has arrays of inner class where price is, then loop to get price.
                            //assign price to a new list
                            //assign also hotstock to a new list.
                            prices.add(object.getPrice);
                            hotstock.add(object);

                            //set the value of all
                            response.setHotstock(hotstock);
                            response.setPrices(prices);

                            dataMutableLiveData.postValue(response);

                        }
                    }).start();
                } else {
                    hotStockLiveData.setValue(null);
                }
            }
        });
        return dataMutableLiveData;
    }
}

然后,你可以创建一个视图模型类

public class AppViewModel extends ViewModel{

    private LiveData<ResponseData> dataLiveData;
    private Repo appRepo;

    public AppViewModel(){
        appRepo = new Repo();
    }

    public LiveData<ResponseData> getLiveData(){
        if(dataLiveData == null){
              dataLiveData = appRepo.getData();
              return dataLiveData;
        }

    }
}

用法

public class MainActivity extends Activity{

    AppViewModel appViewModel;

    public void onCreate(Bundle SavedInstanceState){
        super.onCreate(SavedInstanceState);
        appViewModel = ViewModelProviders.of(this).get(AppViewModel.class);

        appViewModel.getLiveData().observe(this,response -> {
            //here response is an object of type ResponseData.
            //in this response object you can get your arraylist of prices and also arraylist of hotstock


        });
    }
}


文章来源: How can I make one ViewModel class return multiple data types to an activity or a fragment