在没有RXJava的OKHTTP网络呼叫上更新UI

时间:2017-06-23 21:12:53

标签: android networking mvp okhttp

我在模型类中进行了网络调用。在runOnUIThread我希望能够更新用户界面,但我不想将对UI中任何内容的引用传递到我的网络类中。如何更新UI,而不给网络类提供UI类的引用,也不使用像RXJava这样的库?

以下是我正在使用的代码。

公共类WeatherNetwork {

public CurrentWeather getDailyWeather(float lat, float lng) {
    String URL = "";
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(URL)
            .build();

    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

            try {
                String jsonData = response.body().string();
                final String passingData = jsonData;

                if(response.isSuccessful()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            });
                        }
                    });
                }
            } catch(JSONException e) {
                Log.d(ACTIVITY + " JSONEXCEPTION", e.getMessage());
            } catch(IOException e){
                Log.d(ACTIVITY + " IOEXCEPTION", e.getMessage());
            }
        }
    });
    return new CurrentWeather();
}

}

1 个答案:

答案 0 :(得分:1)

您可以将Callback作为方法参数传递。

public void getDailyWeather(float lat, float lng, Callback callback) {

当你入队时,给它。

    client.newCall(request).enqueue(callback);
    return; // This method is done now. Make it void
    // You cannot return from a async method
}

然后,在其他地方,

float lat = 0;
float lng = 0;
api.getDailyWeather(lat, lng, new Callback() {
    @Override
    public void onFailure(Request request, IOException e) {

    }

    @Override
    public void onResponse(Response response) throws IOException {

        try {
            String jsonData = response.body().string();
            final String passingData = jsonData;

            if(response.isSuccessful()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // This is still necessary
                        // But you can now access Views from your UI class   
                    }
                });
            }
        } catch(JSONException e) {
            Log.d(ACTIVITY + " JSONEXCEPTION", e.getMessage());
        } catch(IOException e){
            Log.d(ACTIVITY + " IOEXCEPTION", e.getMessage());
        }
    }
});

如果要清理它,可以定义自己的回调,例如

public interface CurrentWeatherCallback {
   void onWeatherDataReceived(CurrentWeather weather);
}

然后保留你拥有的,但使用其他回调

 final CurrentWeather weather = new CurrentWeather();
 // TODO: Parse JSON 

 runOnUiThread(new Runnable() {
    @Override
    public void run() {
       if (callback != null) callback.onWeatherDataReceived(weather);
    }
  });

无论哪种方式,您都在传递接口,而不是对任何直接UI元素的引用