如何为MVVM模式链接Retrofit和Repository / ViewModel?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何为MVVM模式链接Retrofit和Repository / ViewModel?相关的知识,希望对你有一定的参考价值。

我无法将Retrofit与MVVM架构联系起来。实际上,在阅读了他们只讨论用于SQLite本地数据库的Room的文档之后,我搜索了相同的但是来自Rest服务器的数据。所以,我尝试做类似这样的事情并没有奏效:https://proandroiddev.com/mvvm-architecture-viewmodel-and-livedata-part-1-604f50cda1

我有一个观察ViewModel的Activity:

活动代码:

mFlightPlanViewModel = ViewModelProviders.of(this).get(FlightPlanViewModel.class);
        mFlightPlanViewModel.getFlightPlans().observe(this, (flightPlans) -> {
            Log.d(TAG, "ON_CHANGED");

            mFlightPlanAdapter.setFlightPlans(flightPlans);
        });

ViewModel:

public class FlightPlanViewModel extends androidViewModel {
    private static final String TAG = "FlightPlanViewModel";

    private LiveData<List<FlightPlan>> mFlightPlans;
    private FlightPlanRepository mFlightPlanRepository;

    public FlightPlanViewModel(@NonNull Application application) {
        super(application);
        Log.d(TAG, "CONSTRUCTOR");

        mFlightPlanRepository = FlightPlanRepository.getInstance();
        mFlightPlans = mFlightPlanRepository.getFlightPlans();
    }

    public LiveData<List<FlightPlan>> getFlightPlans() {
        Log.d(TAG, "GET_FLIGHT_PLANS");

        return mFlightPlans;
    }
}

ViewModel回答使用单例模式的Repository:

public class FlightPlanRepository {
    private static final String TAG = "FlightPlanRepository";

    private static FlightPlanRepository instance;
    private RestApi mRestApi;

    private FlightPlanRepository() {
        Log.d(TAG, "CONSTRUCTOR");

        mRestApi = RestDao.getRestDao();
    }

    public static FlightPlanRepository getInstance() {
        Log.d(TAG, "GET_INSTANCE");

        if (instance == null) {
            instance = new FlightPlanRepository();
        }
        return instance;
    }

    public MutableLiveData<List<FlightPlan>> getFlightPlans() {
        Log.d(TAG, "GET_FLIGHT_PLANS");

        final MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();

        mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
            @Override
            public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
                if (response.code() == 200) {
                    List<FlightPlan> temp = response.body();
                    for (FlightPlan flightPlan : temp) {
                        Log.d(TAG + "res", flightPlan.toString());
                    }
                    data.setValue(response.body());
                    Log.d(TAG + "res", response.toString());
                }
            }

            @Override
            public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
                List<FlightPlan> flightPlans = new ArrayList<>();
                flightPlans.add(new FlightPlan(0, "Test", 3.551, 50.52, 3.55122, 50.52625));
                data.setValue(flightPlans);
                Log.d(TAG, t.getMessage());
            }
        });

        return data;
    }
}

存储库使用Retrofit实例:

public class RestDao {
    private static final String BASE_URL = "http://192.168.1.78:8080";
    private static Retrofit instance;

    private static Retrofit getInstance() {
        if (instance == null) {
            instance = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return instance;
    }

    public static RestApi getRestDao() {
        return getInstance().create(RestApi.class);
    }
}

它使用这个界面:

public interface RestApi {
    @GET("/plan/list")
    Call<List<FlightPlan>> getFlightPlanList();
}

代码中不起作用的部分是:

public MutableLiveData<List<FlightPlan>> getFlightPlans() {
    Log.d(TAG, "GET_FLIGHT_PLANS");

    final MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();

    mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
        @Override
        public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
            if (response.code() == 200) {
                List<FlightPlan> temp = response.body();
                for (FlightPlan flightPlan : temp) {
                    Log.d(TAG + "res", flightPlan.toString());
                }
                data.setValue(response.body());
                Log.d(TAG + "res", response.toString());
            }
        }

        @Override
        public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
            List<FlightPlan> flightPlans = new ArrayList<>();
            flightPlans.add(new FlightPlan(0, "Test", 3.551, 50.52, 3.55122, 50.52625));
            data.setValue(flightPlans);
            Log.d(TAG, t.getMessage());
        }
    });

    return data;
}

这返回一个空列表。我认为我理解为什么:调用enqueue()方法发出了一个在另一个Thread中的请求,所以在这里我们返回数据而不等待结果。

所以我的问题是如何链接Retrofit和我的ViewModel?

答案

嘿凯文只是对您的代码进行了一些小改动。而不是MutableLiveData从您的存储库返回LiveData:

public LiveData<List<FlightPlan>> getFlightPlans() {
    Log.d(TAG, "GET_FLIGHT_PLANS");

    final MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();

    mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
        @Override
        public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
            if (response.code() == 200) {
                List<FlightPlan> temp = response.body();
                for (FlightPlan flightPlan : temp) {
                    Log.d(TAG + "res", flightPlan.toString());
                }
                data.postValue(response.body());
                Log.d(TAG + "res", response.toString());
            }
        }

        @Override
        public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
            List<FlightPlan> flightPlans = new ArrayList<>();
            flightPlans.add(new FlightPlan(0, "Test", 3.551, 50.52, 3.55122, 50.52625));
            data.postValue(flightPlans);
            Log.d(TAG, t.getMessage());
        }
    });

    return data;
}
另一答案

如果我这样做:

public LiveData<List<FlightPlan>> getFlightPlans() {
    Log.d(TAG, "GET_FLIGHT_PLANS");

    final MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();


    List<FlightPlan> flightPlans = new ArrayList<>();
    flightPlans.add(new FlightPlan(5, "Test5", 3.551, 50.52, 3.55122, 50.52625));
    data.setValue(flightPlans);
    Log.d(TAG, data.getValue().toString());


    mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
        @Override
        public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
            if (response.code() == 200) {
                List<FlightPlan> temp = response.body();
                for (FlightPlan flightPlan : temp) {
                    Log.d(TAG + "res", flightPlan.toString());
                }
                data.setValue(response.body());
                Log.d(TAG + "res", response.toString());
            }
        }

        @Override
        public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
            List<FlightPlan> flightPlans = new ArrayList<>();
            flightPlans.add(new FlightPlan(0, "Test", 3.551, 50.52, 3.55122, 50.52625));
            data.setValue(flightPlans);
            Log.d(TAG, t.getMessage());
        }
    });

    return data;
}

我可以在Logcat中看到默认值,以及来自我的rest服务器的两个值,但是字符串是空值,int / double是0,并且它不会将两个其余条目添加到recycler视图。

这是我的活动代码:

public class FlightPlanActivity extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, LifecycleOwner {
    private static final String TAG = "FlightPlanActivity";

    private FlightPlanAdapter mFlightPlanAdapter;
    private FlightPlanViewModel mFlightPlanViewModel;

    /**
     * UI
     */
    private FloatingActionButton mAddPlanButton;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_flight_plan);

        Log.d(TAG, "onCreate called");

        initUI();
    }

    private void initUI() {
        this.setTitle("Flight Plans");

        mRecyclerView = findViewById(R.id.flight_plan_list);
        mAddPlanButton = findViewById(R.id.add_flight_plan);
        mSwipeRefreshLayout = findViewById(R.id.refresh_flight_plan_list);

        mAddPlanButton.setOnClickListener(this);
        mSwipeRefreshLayout.setOnRefreshListener(this);

        mFlightPlanAdapter = new FlightPlanAdapter();

        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mFlightPlanAdapter);

        mFlightPlanViewModel = ViewModelProviders.of(this).get(FlightPlanViewModel.class);
        mFlightPlanViewModel.getFlightPlans().observe(this, (flightPlans) -> {
            Log.d(TAG, "ON_CHANGED");

            mFlightPlanAdapter.setFlightPlans(flightPlans);
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == mAddPlanButton.getId()) {
            // TODO: A implémenter
        }
    }

    @Override
    public void onRefresh() {
        mFlightPlanAdapter.setFlightPlans(mFlightPlanViewModel.getFlightPlans().getValue());

        mSwipeRefreshLayout.setRefreshing(false);
    }
}
另一答案

那么,如果我这样做,会有什么反应?

public LiveData<List<FlightPlan>> getFlightPlans() {
    Log.d(TAG, "GET_FLIGHT_PLANS");

    MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();

    mRestApi.getFlightPlanList().enqueue(new Callback<List<FlightPlan>>() {
        @Override
        public void onResponse(Call<List<FlightPlan>> call, Response<List<FlightPlan>> response) {
            if (response.code() == 200) {
                data.setValue(response.body());
            }
        }

        @Override
        public void onFailure(Call<List<FlightPlan>> call, Throwable t) {
            // Do something
        }
    });

    return data;
}

我你运行它,有一个空对象返回,但如果有响应,它会返回一些东西吗?

我试过了:

public LiveData<List<FlightPlan>> getFlightPlans() {
    Log.d(TAG, "GET_FLIGHT_PLANS");

    MutableLiveData<List<FlightPlan>> data = new MutableLiveData<>();
    List<FlightPlan> flightPlans;

    try {
        Response<List<FlightPlan>> response = mRestApi.getFlightPlanList().execute();
        if (response.isSuccessful()) {
            flightPlans = response.body();
        } else {
            Log.d(TAG, "Can't get data !");
            throw new Exception("Can't get data !");
        }
    } catch (Exception e) {
        e.printStackTrace();

        flightPlans = new ArrayList<>();
        flightPlans.add(new FlightPlan(5, "Test5", 3.551, 50.52, 3.55122, 50.52625));
    }

    data.setValue(flightPlans);
    Log.d(TAG, data.getValue().toString());

    return data;
}

现在它在执行行崩溃,因为我在主线程中启动它。所以我必须做一个异步任务,但在哪里?

其他选项:首先创建一个异步任务,将一个setter放到模型视图对象中,当有响应时我调用setter ..这样做有用吗?

谢谢你给我的答案!这非常有帮助。

编辑:为什么在Google文档中有此代码:

public class UserRepository {
    private Webservice webservice;
    // ...
    public LiveData<User> getUser(int userId) {
        // This isn't an optimal implementation. We'll fix it later.
        final MutableLiveData<User> data = new MutableLiveData<>();
        webservice.getUser(userId).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                data.setValue(response.body());
            }

            // Error case is left out for brevity.
        });
        return data;
    }
}

这意味着可以做这样的事情吗?

解决方案

编辑:

How to connect ViewModel with Repository so that data is propagated to the View (MVVM, Livedata)

这对我有很大的帮助!

我找到了解决方案!我很愚蠢:我在gradle文件中插入旧的依赖项!

以上是关于如何为MVVM模式链接Retrofit和Repository / ViewModel?的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI 和 MVVM:当视图模型更改“数据源”(`@Publish items`)本身时,如何为“列表元素更改”设置动画

Android MVVM 和 Retrofit api 响应为空

Android MVVM框架搭建OKHttp + Retrofit + RxJava

Android MVVM框架搭建OKHttp + Retrofit + RxJava

如何为给定的集合创建模式?

如何为新语言编写 emacs 模式?