【问题标题】:How to pass dynamic parameters to rest api in android when using viewmodel使用viewmodel时如何将动态参数传递给android中的rest api
【发布时间】:2019-05-30 13:23:24
【问题描述】:

我正在从 News Api 站点获取新闻详细信息。我正在使用 ViewModel 架构,以便设备在方向更改时不会获取结果。

根据各种教程,我可以使用改造和视图模型购买将结果获取到回收视图,并提供静态参数作为对其余 API 的查询。

private void loadTopHeadlines() {
        ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines("in", 20, 1,
                "api_key");
        response.enqueue(new Callback<TopHeadlinesResponse>() {
            @Override
            public void onResponse(Call<TopHeadlinesResponse> call, Response<TopHeadlinesResponse> response) {
                topHeadlinesResponse.setValue(response.body().getArticles());
            }

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

            }
        });
    }

正如您在创建的 ViewModel 类中看到的,getTopHeadlines() 方法使用静态参数。如何将其更改为动态参数。

静态参数

Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines("in", 20, 1,
                "api_key");

动态参数

Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines(dynamic, dynamic, dynamic,
                "api_key");

【问题讨论】:

  • 这些动态参数从何而来?
  • 第一个参数是基于用户当前位置(“in”)第二个和第三个参数是页面大小和页数。
  • 太棒了,它们是从视图中传递过来的吗?视图模型?
  • 从视图模型传递

标签: android retrofit viewmodel


【解决方案1】:

所以基本上你的方法应该接受这些参数,例如:

private void loadHeadlines(String stringValue, int number, int otherNumer)
//...do some stuff
Call<TopHeadlinesResponse> response = apiInterface.getTopHeadlines(stringValue, number, otherNumber, "api_key");
//rest stays the same
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2021-07-07
    • 2020-01-11
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多