-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement swing workers for fetching weather data
- Loading branch information
Showing
1 changed file
with
47 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
} | ||
} |