小编Cha*_* Li的帖子

如何使用ViewModel和LiveData进行改进API调用

这是我第一次尝试实现MVVM架构,而且我对进行API调用的正确方法感到有些困惑.

目前,我只是尝试从IGDB API进行简单查询,并输出日志中第一项的名称.

我的活动设置如下:

public class PopularGamesActivity extends AppCompatActivity {

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


        PopularGamesViewModel popViewModel = ViewModelProviders.of(this).get(PopularGamesViewModel.class);
        popViewModel.getGameList().observe(this, new Observer<List<Game>>() {
            @Override
            public void onChanged(@Nullable List<Game> gameList) {
                String firstName = gameList.get(0).getName();
                Timber.d(firstName);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我的视图模型设置如下:

public class PopularGamesViewModel extends AndroidViewModel {

    private static final String igdbBaseUrl = "https://api-endpoint.igdb.com/";
    private static final String FIELDS = "id,name,genres,cover,popularity";
    private static final String ORDER = "popularity:desc";
    private static final int LIMIT = 30;

    private LiveData<List<Game>> mGameList; …
Run Code Online (Sandbox Code Playgroud)

android mvvm retrofit android-livedata android-jetpack

16
推荐指数
1
解决办法
9378
查看次数