我知道如何从微调器中获取数据,然后将数据从api传递到存储库,但是在我的情况下,如何在mvvm中正确地从存储库获取数据到viewmodel? 在存储库中,我在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;
}
}
答案 0 :(得分:0)
好的Approuch正在使用ReactiveX来完成这些工作。在Java中,它是RxJava。 Here you could see an example with description。
答案 1 :(得分:0)
MVVM的概念是,视图具有对ViewModel的引用,但ViewModel没有对View的引用。在ViewModel和存储库之间的关系树上也是如此。
您正在使用LiveData作为存储库,这很棒。您需要获取ViewModel才能订阅LiveData,然后将更改的数据流传输到任何观察者(ViewModel)
我发现这是一个很棒的视频:https://www.youtube.com/watch?v=ugpC98LcNqA&t=6s
您还可以查看Google的一些示例:https://github.com/googlesamples/android-architecture