Skip to content

Commit

Permalink
Implement swing workers for fetching weather data
Browse files Browse the repository at this point in the history
  • Loading branch information
daawaan4U committed May 29, 2024
1 parent 810544c commit 92517b5
Showing 1 changed file with 47 additions and 12 deletions.
59 changes: 47 additions & 12 deletions src/main/java/edu/project/services/WeatherService.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,59 @@
package edu.project.services;

import java.io.IOException;

import javax.swing.SwingWorker;

import edu.project.Context;
import edu.project.api.WeatherCurrentData;
import edu.project.api.WeatherForecast5Data;

/**
* Service for handling weather data changes
*/
public class WeatherService {
public WeatherService(Context context) {

// Register listener for location changes
context.store.addLocationListener(position -> {
try {
double lat = position.getLatitude();
double lon = position.getLongitude();

WeatherCurrentData currentData = context.weatherApi.getCurrentWeather(lat, lon);
WeatherForecast5Data forecastData = context.weatherApi.getWeatherForecast(lat, lon);

context.store.setWeatherCurrentData(currentData);
context.store.setWeatherForecast5Data(forecastData);
} catch (Exception e) {
e.printStackTrace();
}
double lat = position.getLatitude();
double lon = position.getLongitude();

// Fetch weather current data from worker thread
new SwingWorker<WeatherCurrentData, Void>() {
@Override
protected WeatherCurrentData doInBackground() throws IOException {
return context.weatherApi.getCurrentWeather(lat, lon);
}

@Override
protected void done() {
try {
context.store.setWeatherCurrentData(get());
} catch (Exception exception) {
exception.printStackTrace();
}

}
}.execute();

// Fetch weather forecast data from worker thread
new SwingWorker<WeatherForecast5Data, Void>() {
@Override
protected WeatherForecast5Data doInBackground() throws IOException {
return context.weatherApi.getWeatherForecast(lat, lon);
}

@Override
protected void done() {
try {
context.store.setWeatherForecast5Data(get());
} catch (Exception exception) {
exception.printStackTrace();
}

}
}.execute();
});
}
}

0 comments on commit 92517b5

Please sign in to comment.