groovy
dependencies {
implementation 'io.reactivex.rxjava3:rxjava:3.0.0'
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
}
public class ApiService {
private final OkHttpClient client;
private final String apiUrl;
public ApiService(OkHttpClient client, String apiUrl) {
this.client = client;
this.apiUrl = apiUrl;
}
public observable<WeatherData> getWeatherData() {
return client.newCall(new Request.Builder()
.url(apiUrl)
.build())
.enqueue(new Callback<ResponseBody>() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response<ResponseBody> response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
WeatherData weatherData = parseWeatherData(response.body().string());
return observable.fromArray(weatherData);
}
});
}
private WeatherData parseWeatherData(String jsonData) {
}
}
public class WeatherObserver extends DisposableObserver<WeatherData> {
private TextView weatherTextView;
public WeatherObserver(TextView weatherTextView) {
this.weatherTextView = weatherTextView;
}
@Override
public void onNext(WeatherData weatherData) {
weatherTextView.setText(weatherData.getWeatherInfo());
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onCompleted() {
}
}
public class MainActivity extends AppCompatActivity {
private TextView weatherTextView;
private ApiService apiService;
private DisposableObserver<WeatherData> weatherObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherTextView = findViewById(R.id.weather_text_view);
apiService = new ApiService(getHttpClient(), "https://api.example.com/weather");
weatherObserver = new WeatherObserver(weatherTextView);
apiService.getWeatherData().subscribe(weatherObserver);
}
@Override
protected void onDestroy() {
super.onDestroy();
weatherObserver.dispose();
}
}