简体   繁体   English

Retrofit 在onResponse方法外返回null?

[英]Retrofit return null outside the onResponse method?

In the onResponse method, the logs returns a value but outside it, it returns null , maybe it does not wait for the response to finish, what could be the problem?onResponse方法中,日志返回一个值,但在它之外,它返回null ,也许它没有等待响应完成,可能是什么问题?

private  MovieResponse AsyncRequest() {
    Retrofit mRetrofit;
    MyWebService mService;
    mRetrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_API_URL)
            .addConverterFactory(GsonConverterFactory.create(new Gson()))
            .build();
    mService = mRetrofit.create(MyWebService.class);
    mService.discoverPopularMovie(Constants.MOVIEDB_APIKEY).enqueue(new Callback<MovieResponse>() {
        @Override
        public void onResponse(@NonNull Call<MovieResponse> call, @NonNull Response<MovieResponse> response) {
            MovieResponse body = response.body();
            movieResponse = body ;
            Log.i(TAG, "onResponse: "+ " movieResponse "+ "HERE" +movieResponse);
        }
        @Override
        public void onFailure(Call<MovieResponse> call, Throwable t) {
            Toast.makeText(context, " failure", Toast.LENGTH_SHORT).show();
            t.printStackTrace();
        }
    });
    return movieResponse ;
}

The problem as you said, It doesn't wait for the response.正如你所说的问题,它不等待响应。 What you need to know that enqueue() calls the request in another thread, so your code runs the request in a different thread than the return will calls.您需要知道 enqueue() 在另一个线程中调用请求,因此您的代码在与 return 调用不同的线程中运行请求。

If you need to wait for the response to return the response body using execute() instead of enqueue()如果您需要等待响应返回响应正文,请使用 execute() 而不是 enqueue()

    try {
            Response<MovieResponse> = mService.discoverPopularMovie(Constants.MOVIEDB_APIKEY).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

note: This mustn't run in UI thread注意:这不能在 UI 线程中运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM