首页 > 解决方案 > MVVM,在存储库中获取上下文,传递值

问题描述

我正在学习 MVVM 并尝试在我的存储库中获取上下文并将值从 MainActivity 传递到存储库类。

我知道您可以通过 Application 在 ViewModel 中获取上下文:

public MyViewModel(Application application) {
        super(application);

        ...
    }

myApi = RetrofitService.getClient(getApplication()).create(ApiInterface.class);

但是它对存储库类是如何工作的,我如何将字符串值(utc)从 MainActivity 传递到存储库类?

我的存储库类有以下示例代码:

private String utc:

public RetroDataRepository() {

public MutableLiveData<TimezoneModel> getTimeZones() {

        final MutableLiveData<TimezoneModel> timezones = new MutableLiveData<>();
        apiInterface = RetrofitService.getClient(context????).create(ApiInterface.class);
        Call<ResponseBody> call = apiInterface.getTimeZone(utc);
        call.enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                String time;
                String utc;
                String region;
                String currentTime;
                String timezoneTitle;

                if(response.body()!=null) {
                    // store TimeZone data to a list
                    Document document = Jsoup.parse(response.body().toString());

                    ....
                }

                isLoading.setValue(false);
            }

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

                Log.e(TAG, "onFailure: ", t);
                isLoading.setValue(false);
                error.setValue(true);
            }
        });

        return timezones;

标签: androidmvvm

解决方案


推荐阅读