【问题标题】:How to correctly in MVVM get the retrofit data from the repository to the viewmodel?如何在 MVVM 中正确获取从存储库到视图模型的改造数据?
【发布时间】:2019-05-27 11:03:48
【问题描述】:

我知道如何从微调器获取数据,然后将数据从 api 传递到存储库,但在我的情况下,如何在 mvvm 中正确地将数据从存储库获取到视图模型? 在存储库中,我在 MutableLiveData 中有 Currency 对象,我想从该对象中获取数据。

public class MainViewModel extends AndroidViewModel {

private CurrencyRepository currencyRepository;
public final ObservableField<String> from = new ObservableField<>();
public final ObservableField<String> to = new ObservableField<>();
public final ObservableFloat value = new ObservableFloat();
private MutableLiveData<Currency> currencyLiveData;
String TAG = "MAIN";

public MainViewModel(Application application) {
   super(application);
   currencyRepository = new CurrencyRepository(application);
}

public void calculateRate() {
    currencyRepository.getCurrency(String.valueOf(from.get()), String.valueOf(to.get()), ApiClient.KEY);

//In this method I'm passing kind of the currency from the spinners in my view
}

存储库:

public class CurrencyRepository {

private ApiInterface apiInterface;
private  String apiKey = ApiClient.KEY;

public CurrencyRepository(Application application) {
   apiInterface = ApiClient.getClient();
}

public LiveData<Currency> getCurrency(String base, String target, String apiKey) {

    final MutableLiveData<Currency> data = new MutableLiveData<>();
    apiInterface.getCurrentCurrency(base, target, apiKey).enqueue(new Callback<Currency>() {
        @Override
        public void onResponse(Call<Currency> call, Response<Currency> response) {
            data.setValue(response.body());

        }

        @Override
        public void onFailure(Call<Currency> call, Throwable t) {

        }
    });
    return data;
}

}

【问题讨论】:

    标签: android mvvm retrofit


    【解决方案1】:

    很好的方法是用 ReactiveX 做这些事情。在 Java 中它是 RxJava。 Here you could see an example with description.

    【讨论】:

    • Livedata 怎么样?有什么办法吗?
    【解决方案2】:

    MVVM 的概念是 View 具有对 ViewModel 的引用,但 ViewModel 没有对 View 的引用。这同样适用于 ViewModel 和 Repository 之间的关系。

    您正在使用 LiveData 作为存储库,这很棒。您需要让 ViewModel 订阅 LiveData,然后将更改的数据流式传输到任何观察者(ViewModel)

    我发现这是一个非常值得观看的视频:https://www.youtube.com/watch?v=ugpC98LcNqA&t=6s

    您还可以查看 Google 的一些示例:https://github.com/googlesamples/android-architecture

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2012-12-11
      • 2011-04-13
      • 2014-05-27
      • 2017-12-24
      • 2019-06-13
      相关资源
      最近更新 更多