├── .gitignore
├── .idea
├── .gitignore
├── androidTestResultsUserPreferences.xml
├── compiler.xml
├── deploymentTargetDropDown.xml
├── gradle.xml
├── inspectionProfiles
│ └── Project_Default.xml
├── kotlinc.xml
├── migrations.xml
├── misc.xml
├── sonarlint
│ └── issuestore
│ │ ├── 4
│ │ └── 9
│ │ │ └── 49714c180cf12e6bb0fb0f86b8a2e6b52e75ed1d
│ │ ├── 5
│ │ └── d
│ │ │ └── 5dd0036e6eaabc1cbb2545b80a0bfffc2708a45b
│ │ ├── 9
│ │ └── e
│ │ │ └── 9ea6805d7eed655f05d5c8957775a6e66211bf8e
│ │ ├── f
│ │ ├── 0
│ │ │ └── f07866736216be0ee2aba49e392191aeae700a35
│ │ └── 4
│ │ │ └── f4a01d6a4fcb971362ec00a83903fd3902f52164
│ │ └── index.pb
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle.kts
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── weather
│ │ └── app
│ │ ├── HiltTestRunner.kt
│ │ ├── app_feature
│ │ └── presentation
│ │ │ ├── HomeScreenE2ETest.kt
│ │ │ ├── SettingsScreenE2ETest.kt
│ │ │ └── data
│ │ │ └── locale
│ │ │ └── AppDaoTest.kt
│ │ └── di
│ │ └── TestAppModule.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── ic_launcher-playstore.png
│ ├── java
│ │ └── com
│ │ │ └── weather
│ │ │ └── app
│ │ │ ├── MyApp.kt
│ │ │ ├── data
│ │ │ ├── data_source
│ │ │ │ ├── local
│ │ │ │ │ ├── AppDao.kt
│ │ │ │ │ ├── AppDatabase.kt
│ │ │ │ │ ├── CityEntity.kt
│ │ │ │ │ ├── CityEntityMapper.kt
│ │ │ │ │ └── WeatherDataStore.kt
│ │ │ │ └── remote
│ │ │ │ │ ├── CityDtoMapper.kt
│ │ │ │ │ ├── RetrofitService.kt
│ │ │ │ │ └── response
│ │ │ │ │ ├── CurrentConditionsResponse.kt
│ │ │ │ │ ├── DailyForecastResponse.kt
│ │ │ │ │ ├── HourlyForecastData.kt
│ │ │ │ │ └── SearchResponse.kt
│ │ │ └── repository
│ │ │ │ └── AppRepositoryImpl.kt
│ │ │ ├── di
│ │ │ ├── AppModule.kt
│ │ │ ├── LocalModule.kt
│ │ │ └── NetworkModule.kt
│ │ │ ├── domain
│ │ │ ├── DataState.kt
│ │ │ ├── model
│ │ │ │ └── City.kt
│ │ │ ├── repository
│ │ │ │ └── AppRepository.kt
│ │ │ └── use_case
│ │ │ │ ├── AddCityOffline.kt
│ │ │ │ ├── AppUseCases.kt
│ │ │ │ ├── DeleteCity.kt
│ │ │ │ ├── GetCities.kt
│ │ │ │ ├── GetCurrentConditions.kt
│ │ │ │ ├── GetDailyForecasts.kt
│ │ │ │ ├── GetHourlyForecasts.kt
│ │ │ │ └── GetSearchResults.kt
│ │ │ ├── extension
│ │ │ ├── DateExtension.kt
│ │ │ └── WeatherIcons.kt
│ │ │ ├── navigation
│ │ │ ├── AppLevelNavigation.kt
│ │ │ ├── AppNavigationDestination.kt
│ │ │ └── NavigateSingleTop.kt
│ │ │ ├── presentation
│ │ │ ├── MainActivity.kt
│ │ │ ├── components
│ │ │ │ ├── CityItem.kt
│ │ │ │ ├── ConnectivityMonitor.kt
│ │ │ │ ├── DailyForecastItem.kt
│ │ │ │ ├── DisposableEffectWithLifeCycle.kt
│ │ │ │ ├── GenericDialog.kt
│ │ │ │ └── HourlyForecastItem.kt
│ │ │ ├── home_screen
│ │ │ │ ├── HomeScreen.kt
│ │ │ │ ├── HomeScreenEvent.kt
│ │ │ │ ├── HomeScreenState.kt
│ │ │ │ ├── HomeScreenViewModel.kt
│ │ │ │ └── navigation
│ │ │ │ │ └── HomeScreenDestination.kt
│ │ │ ├── navigation
│ │ │ │ └── MyApp.kt
│ │ │ ├── search_screen
│ │ │ │ ├── SearchScreen.kt
│ │ │ │ ├── SearchScreenEvent.kt
│ │ │ │ ├── SearchScreenState.kt
│ │ │ │ ├── SearchScreenViewModel.kt
│ │ │ │ └── navigation
│ │ │ │ │ └── SearchScreenDestination.kt
│ │ │ ├── settings_screen
│ │ │ │ ├── SettingsScreen.kt
│ │ │ │ └── navigation
│ │ │ │ │ └── SettingsScreenDestination.kt
│ │ │ └── weather_animation_screen
│ │ │ │ ├── WeatherAnimationScreen.kt
│ │ │ │ └── navigation
│ │ │ │ └── WeatherAnimationScreenDestination.kt
│ │ │ ├── testtags
│ │ │ └── TestTags.kt
│ │ │ ├── theme
│ │ │ ├── Color.kt
│ │ │ ├── Shape.kt
│ │ │ ├── Theme.kt
│ │ │ └── Type.kt
│ │ │ └── util
│ │ │ ├── ConnectionFlowCallback.kt
│ │ │ ├── ConnectivityManager.kt
│ │ │ ├── Constants.kt
│ │ │ ├── DialogQueue.kt
│ │ │ ├── DoesNetworkHaveInternet.kt
│ │ │ ├── Extensions.kt
│ │ │ ├── ImageUtils.kt
│ │ │ ├── SavedStateHandleExtensions.kt
│ │ │ ├── SnackbarUtil.kt
│ │ │ └── Utils.kt
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ ├── accuweather_splash_brand.png
│ │ ├── app_icon.png
│ │ ├── clouds.png
│ │ ├── cloudy.png
│ │ ├── cloudy_night.png
│ │ ├── ic_launcher_background.xml
│ │ ├── img.png
│ │ ├── partly_cloudy.png
│ │ ├── rain_lightning.png
│ │ ├── rainy.png
│ │ ├── sunny.png
│ │ └── sunny_night.png
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.webp
│ │ ├── ic_launcher_foreground.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.webp
│ │ ├── ic_launcher_foreground.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.webp
│ │ ├── ic_launcher_foreground.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.webp
│ │ ├── ic_launcher_foreground.webp
│ │ └── ic_launcher_round.webp
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.webp
│ │ ├── ic_launcher_foreground.webp
│ │ └── ic_launcher_round.webp
│ │ ├── values-night
│ │ ├── strings.xml
│ │ └── themes.xml
│ │ ├── values-v31
│ │ └── splash_theme.xml
│ │ ├── values
│ │ ├── colors.xml
│ │ ├── ic_launcher_background.xml
│ │ ├── splash_theme.xml
│ │ ├── strings.xml
│ │ └── themes.xml
│ │ └── xml
│ │ └── network_security_config.xml
│ └── test
│ └── java
│ └── com
│ └── weather
│ └── app
│ └── app_feature
│ ├── MainDispatcherRule.kt
│ ├── data
│ └── repository
│ │ └── FakeWeatherAppRepository.kt
│ ├── domain
│ └── use_case
│ │ ├── AddCityOfflineTest.kt
│ │ ├── DeleteCityTest.kt
│ │ ├── GetCurrentConditionsTest.kt
│ │ ├── GetDailyForecastsTest.kt
│ │ ├── GetHourlyForecastsTest.kt
│ │ └── GetSearchResultsTest.kt
│ ├── presentation
│ └── home_screen
│ │ └── HomeScreenViewModelTest.kt
│ └── responses
│ └── MockWebServerResponses.kt
├── build.gradle.kts
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle.kts
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/androidTestResultsUserPreferences.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
164 |
165 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/deploymentTargetDropDown.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/migrations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/sonarlint/issuestore/4/9/49714c180cf12e6bb0fb0f86b8a2e6b52e75ed1d:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/.idea/sonarlint/issuestore/4/9/49714c180cf12e6bb0fb0f86b8a2e6b52e75ed1d
--------------------------------------------------------------------------------
/.idea/sonarlint/issuestore/5/d/5dd0036e6eaabc1cbb2545b80a0bfffc2708a45b:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/.idea/sonarlint/issuestore/5/d/5dd0036e6eaabc1cbb2545b80a0bfffc2708a45b
--------------------------------------------------------------------------------
/.idea/sonarlint/issuestore/9/e/9ea6805d7eed655f05d5c8957775a6e66211bf8e:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/.idea/sonarlint/issuestore/9/e/9ea6805d7eed655f05d5c8957775a6e66211bf8e
--------------------------------------------------------------------------------
/.idea/sonarlint/issuestore/f/0/f07866736216be0ee2aba49e392191aeae700a35:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/.idea/sonarlint/issuestore/f/0/f07866736216be0ee2aba49e392191aeae700a35
--------------------------------------------------------------------------------
/.idea/sonarlint/issuestore/f/4/f4a01d6a4fcb971362ec00a83903fd3902f52164:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/.idea/sonarlint/issuestore/f/4/f4a01d6a4fcb971362ec00a83903fd3902f52164
--------------------------------------------------------------------------------
/.idea/sonarlint/issuestore/index.pb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/.idea/sonarlint/issuestore/index.pb
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | 
3 |
4 | # WeatherApp 🌟
5 |
6 | [](LICENSE)
7 | 
8 | [](https://ktlint.github.io/)
9 |
10 | ## Overview 🚀
11 |
12 |
13 | Welcome to the WeatherApp repository! This Android project is a showcase of cutting-edge technologies and a demonstration of elegant UI design using Jetpack Compose.
14 |
15 | ## Features ✨
16 |
17 | - 🏗 **Clean Architecture:** The project follows a clean and modular architecture, making it easy to understand and extend.
18 | - 🎨 **Compose UI** Modern UI tool kit
19 | - 🚀 **Kotlin:** Written entirely in Kotlin, taking advantage of its conciseness and expressiveness.
20 | - 🗄️ **Coroutines & Flow:** Leverage the power of Kotlin Coroutines and Flow for asynchronous programming.
21 | - 🚀 **Room Database:** Persist data with Room, providing a robust and efficient local database solution.
22 | - 🚀 **Moshi:** Utilize Moshi for efficient JSON parsing, ensuring seamless communication with APIs.
23 | - 🌙 **Dark/Light Theme:** Enjoy a seamless user experience with the option to switch between dark and light themes.
24 | - 🌐 **Splash API Integration:** Connect to a Splash API to dynamically load and display stunning images.
25 | - 💾 **DataStore** Modern SharedPref way with flow integration
26 | - 🔬 **Unit testing** Introducing unit tests with Junit and mockservers
27 | - ✅ **UI testing** Introducing UI tests with compose rule
28 |
29 | ## Connect with Me 🌐
30 |
31 | Let's connect! Feel free to reach out on LinkedIn.
32 |
33 | LinkedIn: https://www.linkedin.com/in/abualgait/
34 |
35 | Happy coding! 🚀✨
36 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("com.android.application")
3 | id("org.jetbrains.kotlin.android")
4 | id("kotlin-android")
5 | id("kotlin-parcelize")
6 | id("kotlin-kapt")
7 | id("com.google.dagger.hilt.android")
8 | id("com.google.devtools.ksp")
9 | }
10 |
11 | android {
12 | namespace = "com.weather.app"
13 | compileSdk = 34
14 |
15 | defaultConfig {
16 | applicationId = "com.weather.app"
17 | minSdk = 21
18 | //noinspection EditedTargetSdkVersion
19 | targetSdk = 34
20 | versionCode = 1
21 | versionName = "1.0"
22 |
23 | testInstrumentationRunner = "com.weather.app.HiltTestRunner"
24 | vectorDrawables {
25 | useSupportLibrary = true
26 | }
27 |
28 | }
29 |
30 | buildTypes {
31 | release {
32 | isMinifyEnabled = false
33 | proguardFiles(
34 | getDefaultProguardFile("proguard-android-optimize.txt"),
35 | "proguard-rules.pro"
36 | )
37 | }
38 | }
39 | compileOptions {
40 | sourceCompatibility = JavaVersion.VERSION_17
41 | targetCompatibility = JavaVersion.VERSION_17
42 | }
43 | kotlinOptions {
44 | jvmTarget = "17"
45 | }
46 | buildFeatures {
47 | compose = true
48 | buildConfig = true
49 | }
50 | composeOptions {
51 | kotlinCompilerExtensionVersion = "1.5.3"
52 | }
53 | packaging {
54 | resources {
55 | excludes += "/META-INF/{AL2.0,LGPL2.1}"
56 | excludes += "META-INF/DEPENDENCIES"
57 | excludes += "META-INF/LICENSE"
58 | excludes += "META-INF/LICENSE.txt"
59 | excludes += "META-INF/license.txt"
60 | excludes += "META-INF/NOTICE"
61 | excludes += "META-INF/NOTICE.txt"
62 | excludes += "META-INF/notice.txt"
63 | excludes += "META-INF/ASL2.0"
64 | excludes += "META-INF/*.kotlin_module"
65 | excludes += "META-INF/LICENSE.md"
66 | excludes += "META-INF/LICENSE-notice.md"
67 | }
68 | }
69 | }
70 |
71 | dependencies {
72 |
73 |
74 | implementation("androidx.core:core-ktx:1.12.0")
75 | implementation("androidx.appcompat:appcompat:1.6.1")
76 | implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
77 | androidTestImplementation("androidx.test.ext:junit:1.1.5")
78 | androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
79 |
80 | //Splash-screen API
81 | implementation("androidx.core:core-splashscreen:1.0.1")
82 |
83 | //Compose dependencies
84 | implementation("androidx.activity:activity-compose:1.8.1")
85 | implementation(platform("androidx.compose:compose-bom:2023.09.01"))
86 | implementation("androidx.compose.ui:ui")
87 | implementation("androidx.compose.ui:ui-graphics")
88 | implementation("androidx.compose.ui:ui-tooling-preview")
89 | implementation("androidx.compose.material3:material3")
90 | implementation("androidx.compose.material:material:1.5.4")
91 |
92 | val composeVersion = "1.5.4"
93 | androidTestImplementation("androidx.compose.ui:ui-test-junit4:${composeVersion}")
94 | debugImplementation("androidx.compose.ui:ui-tooling:${composeVersion}")
95 |
96 | implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0-rc01")
97 | implementation("androidx.navigation:navigation-compose:2.7.5")
98 | implementation("androidx.hilt:hilt-navigation-compose:1.1.0")
99 |
100 | //Coroutines
101 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
102 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
103 |
104 | //Dagger - Hilt
105 | implementation("com.google.dagger:hilt-android:2.48.1")
106 | kapt("com.google.dagger:hilt-android-compiler:2.48.1")
107 | kapt("androidx.hilt:hilt-compiler:1.1.0")
108 |
109 | //Room
110 | val room = "2.6.0"
111 | implementation("androidx.room:room-runtime:${room}")
112 | implementation("androidx.room:room-ktx:${room}")
113 | ksp("androidx.room:room-compiler:${room}")
114 |
115 | //Datastore
116 | implementation("androidx.datastore:datastore-preferences:1.0.0")
117 |
118 | //Retrofit
119 | val retrofit = "2.9.0"
120 | val okHttp = "4.11.0"
121 | implementation("com.squareup.retrofit2:retrofit:${retrofit}")
122 | implementation("com.squareup.retrofit2:converter-moshi:${retrofit}")
123 | implementation("com.squareup.okhttp3:okhttp:${okHttp}")
124 | implementation("com.squareup.okhttp3:logging-interceptor:${okHttp}")
125 |
126 | // Moshi for parsing the JSON format
127 | val moshiVersion = "1.12.0"
128 | implementation("com.squareup.moshi:moshi:$moshiVersion")
129 | implementation("com.squareup.moshi:moshi-kotlin:$moshiVersion")
130 | ksp("com.squareup.moshi:moshi-kotlin-codegen:$moshiVersion")
131 |
132 | // Local unit tests
133 | testImplementation("androidx.test:core:1.5.0")
134 | testImplementation("junit:junit:4.13.2")
135 | testImplementation("androidx.arch.core:core-testing:2.2.0")
136 | testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
137 | testImplementation("com.google.truth:truth:1.1.3")
138 | debugImplementation("androidx.compose.ui:ui-test-manifest:1.6.0-beta02")
139 | testImplementation("com.squareup.okhttp3:mockwebserver:${okHttp}")
140 | testImplementation("com.squareup.okhttp3:okhttp:${okHttp}")
141 | testImplementation("io.mockk:mockk:1.13.8")
142 | testImplementation("androidx.test.ext:junit:1.1.5")
143 | testImplementation ("app.cash.turbine:turbine:1.0.0")
144 |
145 | // Instrumentation tests
146 | androidTestImplementation("com.google.dagger:hilt-android-testing:2.48.1")
147 | kaptAndroidTest("com.google.dagger:hilt-android-compiler:2.48.1")
148 | androidTestImplementation("junit:junit:4.13.2")
149 | androidTestImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
150 | androidTestImplementation("androidx.arch.core:core-testing:2.2.0")
151 | androidTestImplementation("com.google.truth:truth:1.1.3")
152 | androidTestImplementation("androidx.test.ext:junit:1.1.5")
153 | androidTestImplementation("androidx.test:core-ktx:1.5.0")
154 | androidTestImplementation("androidx.test:runner:1.5.2")
155 | androidTestImplementation("com.squareup.okhttp3:mockwebserver:${okHttp}")
156 | androidTestImplementation("com.squareup.okhttp3:okhttp:${okHttp}")
157 |
158 |
159 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.kts.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/weather/app/HiltTestRunner.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app
2 |
3 | import android.app.Application
4 | import android.content.Context
5 | import androidx.test.runner.AndroidJUnitRunner
6 | import dagger.hilt.android.testing.HiltTestApplication
7 |
8 | class HiltTestRunner : AndroidJUnitRunner() {
9 |
10 | override fun newApplication(
11 | cl: ClassLoader?,
12 | className: String?,
13 | context: Context?
14 | ): Application {
15 | return super.newApplication(cl, HiltTestApplication::class.java.name, context)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/weather/app/app_feature/presentation/HomeScreenE2ETest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.presentation
2 |
3 | import androidx.activity.compose.setContent
4 | import androidx.compose.animation.ExperimentalAnimationApi
5 | import androidx.compose.ui.test.ExperimentalTestApi
6 | import androidx.compose.ui.test.assertCountEquals
7 | import androidx.compose.ui.test.assertIsDisplayed
8 | import androidx.compose.ui.test.hasTestTag
9 | import androidx.compose.ui.test.junit4.createAndroidComposeRule
10 | import androidx.compose.ui.test.onAllNodesWithTag
11 | import androidx.compose.ui.test.onNodeWithTag
12 | import androidx.compose.ui.test.performClick
13 | import androidx.lifecycle.lifecycleScope
14 | import com.weather.app.di.AppModule
15 | import com.weather.app.di.LocalModule
16 | import com.weather.app.di.NetworkModule
17 | import com.weather.app.presentation.MainActivity
18 | import com.weather.app.presentation.navigation.MyApp
19 | import com.weather.app.testtags.TestTags
20 | import com.weather.app.theme.AppTheme
21 | import dagger.hilt.android.testing.HiltAndroidRule
22 | import dagger.hilt.android.testing.HiltAndroidTest
23 | import dagger.hilt.android.testing.UninstallModules
24 | import kotlinx.coroutines.delay
25 | import kotlinx.coroutines.launch
26 | import org.junit.Before
27 | import org.junit.Rule
28 | import org.junit.Test
29 |
30 | @HiltAndroidTest
31 | @UninstallModules(AppModule::class, LocalModule::class, NetworkModule::class)
32 | class HomeScreenE2ETest {
33 |
34 | @get:Rule(order = 0)
35 | val hiltRule = HiltAndroidRule(this)
36 |
37 | @get:Rule(order = 1)
38 | val composeRule = createAndroidComposeRule()
39 |
40 | @ExperimentalAnimationApi
41 | @Before
42 | fun setUp() {
43 | hiltRule.inject()
44 | composeRule.activity.setContent {
45 | AppTheme(
46 | isNetworkAvailable = false
47 | ) {
48 | MyApp(isNetworkAvailable = false, isDarkTheme = false)
49 | }
50 | }
51 | }
52 |
53 | @Test
54 | fun tearDown() {
55 |
56 |
57 | }
58 |
59 | @Test
60 | fun testCustomSwitch() {
61 | composeRule.activity.lifecycleScope.launch {
62 | delay(1000)
63 | composeRule.onNodeWithTag(TestTags.LightModeImageTag).assertIsDisplayed()
64 | composeRule.onNodeWithTag(TestTags.CustomSwitch).performClick()
65 | delay(300)
66 | composeRule.onNodeWithTag(TestTags.DarkModeImageTag).assertIsDisplayed()
67 | }
68 |
69 | }
70 |
71 | @Test
72 | fun testSearchIconNavigation() {
73 | composeRule.onNodeWithTag(TestTags.IconSearch).assertIsDisplayed()
74 | composeRule.onNodeWithTag(TestTags.IconSearch).performClick()
75 | composeRule.onNodeWithTag(TestTags.IconBack).assertIsDisplayed()
76 |
77 | }
78 |
79 | @OptIn(ExperimentalTestApi::class)
80 | @Test
81 | fun testNoDataFound() {
82 | composeRule.onAllNodesWithTag(TestTags.NoDataFound).assertCountEquals(3)
83 | composeRule.onNodeWithTag(TestTags.Reload + "No current conditions found").performClick()
84 | composeRule.waitUntilExactlyOneExists(hasTestTag(TestTags.SnackBar))
85 | composeRule.onNodeWithTag(TestTags.SnackBar).assertIsDisplayed()
86 |
87 | }
88 |
89 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/weather/app/app_feature/presentation/SettingsScreenE2ETest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.presentation
2 |
3 | import androidx.activity.compose.setContent
4 | import androidx.compose.animation.ExperimentalAnimationApi
5 | import androidx.compose.ui.test.ExperimentalTestApi
6 | import androidx.compose.ui.test.assertIsDisplayed
7 | import androidx.compose.ui.test.assertIsNotDisplayed
8 | import androidx.compose.ui.test.hasTestTag
9 | import androidx.compose.ui.test.junit4.createAndroidComposeRule
10 | import androidx.compose.ui.test.onNodeWithTag
11 | import androidx.compose.ui.test.performClick
12 | import androidx.compose.ui.test.performTextInput
13 | import androidx.lifecycle.lifecycleScope
14 | import com.weather.app.di.AppModule
15 | import com.weather.app.di.LocalModule
16 | import com.weather.app.di.NetworkModule
17 | import com.weather.app.presentation.MainActivity
18 | import com.weather.app.presentation.navigation.MyApp
19 | import com.weather.app.testtags.TestTags
20 | import com.weather.app.theme.AppTheme
21 | import dagger.hilt.android.testing.HiltAndroidRule
22 | import dagger.hilt.android.testing.HiltAndroidTest
23 | import dagger.hilt.android.testing.UninstallModules
24 | import kotlinx.coroutines.delay
25 | import kotlinx.coroutines.launch
26 | import org.junit.Before
27 | import org.junit.Rule
28 | import org.junit.Test
29 |
30 | @HiltAndroidTest
31 | @UninstallModules(AppModule::class, LocalModule::class, NetworkModule::class)
32 | class SettingsScreenE2ETest {
33 |
34 | @get:Rule(order = 0)
35 | val hiltRule = HiltAndroidRule(this)
36 |
37 | @get:Rule(order = 1)
38 | val composeRule = createAndroidComposeRule()
39 |
40 | @ExperimentalAnimationApi
41 | @Before
42 | fun setUp() {
43 | hiltRule.inject()
44 | composeRule.activity.setContent {
45 | AppTheme(
46 | isNetworkAvailable = false
47 | ) {
48 | MyApp(isNetworkAvailable = false, isDarkTheme = false)
49 | }
50 | }
51 | }
52 |
53 | @OptIn(ExperimentalTestApi::class)
54 | @Test
55 | fun testNoDataFound() {
56 |
57 | composeRule.apply {
58 | onNodeWithTag(TestTags.IconSearch).assertIsDisplayed()
59 | onNodeWithTag(TestTags.IconSearch).performClick()
60 | onNodeWithTag(TestTags.IconBack).assertIsDisplayed()
61 |
62 | onNodeWithTag(TestTags.SearchField).assertIsDisplayed()
63 | onNodeWithTag(TestTags.ClearIcon).assertIsNotDisplayed()
64 | onNodeWithTag(TestTags.RecentLocationsText).assertIsNotDisplayed()
65 |
66 |
67 | onNodeWithTag(TestTags.SearchField).performTextInput("Ca")
68 | onNodeWithTag(TestTags.ClearIcon).assertIsDisplayed()
69 | onNodeWithTag(TestTags.RecentLocationsText).assertIsNotDisplayed()
70 |
71 | onNodeWithTag(TestTags.SearchField).performTextInput("iro")
72 |
73 | waitUntilExactlyOneExists(hasTestTag(TestTags.SnackBar))
74 | activity.lifecycleScope.launch {
75 | delay(3000)
76 | onNodeWithTag(TestTags.SnackBar).assertIsDisplayed()
77 | }
78 |
79 |
80 | }
81 |
82 | }
83 |
84 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/weather/app/app_feature/presentation/data/locale/AppDaoTest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.presentation.data.locale
2 |
3 | import androidx.arch.core.executor.testing.InstantTaskExecutorRule
4 | import androidx.room.Room
5 | import androidx.test.core.app.ApplicationProvider
6 | import androidx.test.ext.junit.runners.AndroidJUnit4
7 | import com.google.common.truth.Truth.assertThat
8 | import com.weather.app.data.data_source.local.AppDao
9 | import com.weather.app.data.data_source.local.AppDatabase
10 | import com.weather.app.data.data_source.local.CityEntity
11 | import kotlinx.coroutines.flow.first
12 | import kotlinx.coroutines.test.runTest
13 | import org.junit.After
14 | import org.junit.Before
15 | import org.junit.Rule
16 | import org.junit.Test
17 | import org.junit.runner.RunWith
18 |
19 | @RunWith(AndroidJUnit4::class)
20 | class AppDaoTest {
21 |
22 | @Rule
23 | @JvmField
24 | val instantExecutorRule = InstantTaskExecutorRule()
25 |
26 | private lateinit var weatherDatabase: AppDatabase
27 | private lateinit var appDao: AppDao
28 |
29 | @Before
30 | fun setUp() {
31 | weatherDatabase = Room.inMemoryDatabaseBuilder(
32 | ApplicationProvider.getApplicationContext(),
33 | AppDatabase::class.java
34 | )
35 | .allowMainThreadQueries()
36 | .build()
37 |
38 | appDao = weatherDatabase.appDao
39 | }
40 |
41 | @After
42 | fun tearDown() {
43 | weatherDatabase.close()
44 | }
45 |
46 | @Test
47 | fun insertCity_ReturnSuccess() = runTest {
48 | val city = CityEntity("1", "Cairo", "Egypt", "Cairo")
49 | appDao.insertEntity(city)
50 | assertThat(appDao.getEntities().first()).isEqualTo(arrayListOf(city))
51 |
52 | }
53 |
54 | @Test
55 | fun deleteCity_ReturnSuccess() = runTest {
56 | val city = CityEntity("1", "Cairo", "Egypt", "Cairo")
57 | appDao.insertEntity(city)
58 | assertThat(appDao.getEntities().first()).isEqualTo(arrayListOf(city))
59 | appDao.deleteEntity(city)
60 | assertThat(appDao.getEntities().first().size).isEqualTo(0)
61 | }
62 |
63 | @Test
64 | fun getCity_ReturnSuccess() = runTest {
65 | val city = CityEntity("1", "Cairo", "Egypt", "Cairo")
66 | appDao.insertEntity(city)
67 | val result = appDao.getEntityById(1)
68 | assertThat(result).isNotNull()
69 | assertThat(result?.id).isEqualTo("1")
70 | }
71 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/weather/app/di/TestAppModule.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.di
2 |
3 | import android.app.Application
4 | import androidx.room.Room
5 | import com.squareup.moshi.Moshi
6 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
7 | import com.weather.app.data.data_source.local.AppDatabase
8 | import com.weather.app.data.data_source.remote.RetrofitService
9 | import com.weather.app.data.repository.AppRepositoryImpl
10 | import com.weather.app.domain.repository.AppRepository
11 | import com.weather.app.domain.use_case.*
12 | import com.weather.app.util.BASE_URL
13 | import dagger.Module
14 | import dagger.Provides
15 | import dagger.hilt.InstallIn
16 | import dagger.hilt.components.SingletonComponent
17 | import okhttp3.OkHttpClient
18 | import okhttp3.logging.HttpLoggingInterceptor
19 | import retrofit2.Retrofit
20 | import retrofit2.converter.moshi.MoshiConverterFactory
21 | import javax.inject.Singleton
22 |
23 | @Module
24 | @InstallIn(SingletonComponent::class)
25 | object TestAppModule {
26 |
27 | @Provides
28 | @Singleton
29 | fun provideAppDatabase(app: Application): AppDatabase {
30 | return Room.inMemoryDatabaseBuilder(
31 | app,
32 | AppDatabase::class.java,
33 | ).build()
34 | }
35 |
36 | @Provides
37 | @Singleton
38 | fun provideOkHttpClient(): OkHttpClient {
39 | return OkHttpClient.Builder().apply {
40 | val loggingInterceptor = HttpLoggingInterceptor()
41 | loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
42 | addInterceptor(loggingInterceptor)
43 | }.build()
44 | }
45 |
46 | @Singleton
47 | @Provides
48 | fun providesMoshi() = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
49 |
50 | @Singleton
51 | @Provides
52 | fun provideService(okHttpClient: OkHttpClient, mosh: Moshi): RetrofitService {
53 | return Retrofit.Builder()
54 | .baseUrl(BASE_URL)
55 | .client(okHttpClient)
56 | .addConverterFactory(MoshiConverterFactory.create(mosh))
57 | .build()
58 | .create(RetrofitService::class.java)
59 | }
60 |
61 | @Provides
62 | @Singleton
63 | fun provideAppRepository(
64 | db: AppDatabase, retrofitService: RetrofitService,
65 | ): AppRepository {
66 | return AppRepositoryImpl(db.appDao, retrofitService)
67 | }
68 |
69 | @Provides
70 | @Singleton
71 | fun provideAppUseCases(repository: AppRepository): AppUseCases {
72 | return AppUseCases(
73 | getSearchResults = GetSearchResults(repository),
74 | getCurrentConditions = GetCurrentConditions(repository),
75 | addCityOffline = AddCityOffline(repository),
76 | getCities = GetCities(repository),
77 | deleteCity = DeleteCity(repository),
78 | hourlyForecasts = GetHourlyForecasts(repository),
79 | dailyForecasts = GetDailyForecasts(repository)
80 | )
81 | }
82 |
83 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/ic_launcher-playstore.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/ic_launcher-playstore.png
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/MyApp.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app
2 |
3 | import android.app.Application
4 | import dagger.hilt.android.HiltAndroidApp
5 |
6 | @HiltAndroidApp
7 | class MyApp : Application()
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/local/AppDao.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.local
2 |
3 | import androidx.room.*
4 | import kotlinx.coroutines.flow.Flow
5 |
6 | @Dao
7 | interface AppDao {
8 |
9 | @Query("SELECT * FROM city_entity")
10 | fun getEntities(): Flow>
11 |
12 | @Query("SELECT * FROM city_entity WHERE id = :id")
13 | suspend fun getEntityById(id: Int): CityEntity?
14 |
15 | @Insert(onConflict = OnConflictStrategy.REPLACE)
16 | suspend fun insertEntity(entity: CityEntity)
17 |
18 | @Delete
19 | suspend fun deleteEntity(entity: CityEntity)
20 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/local/AppDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.local
2 |
3 | import androidx.room.Database
4 | import androidx.room.RoomDatabase
5 |
6 | @Database(
7 | entities = [CityEntity::class],
8 | version = 1,
9 | exportSchema = false // edit this before production, create migration schema
10 | )
11 | abstract class AppDatabase : RoomDatabase() {
12 |
13 | abstract val appDao: AppDao
14 |
15 | companion object {
16 | const val DATABASE_NAME = "app_db"
17 | }
18 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/local/CityEntity.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.local
2 |
3 | import androidx.room.Entity
4 | import androidx.room.PrimaryKey
5 |
6 | @Entity(tableName = "city_entity")
7 | data class CityEntity(
8 | @PrimaryKey val id: String,
9 | val localizedName: String,
10 | val country: String,
11 | val administrativeArea: String
12 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/local/CityEntityMapper.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.local
2 |
3 |
4 | import com.weather.app.domain.model.City
5 |
6 |
7 | fun CityEntity.mapToDomainModel(): City {
8 | return City(
9 | id = id,
10 | localizedName = localizedName,
11 | country = country,
12 | administrativeArea = administrativeArea,
13 |
14 | )
15 | }
16 |
17 | fun City.mapFromDomainModel(): CityEntity {
18 | return CityEntity(
19 | id = id,
20 | localizedName = localizedName,
21 | country = country,
22 | administrativeArea = administrativeArea
23 | )
24 | }
25 |
26 | fun List.fromEntityList(): List {
27 | return map { it.mapToDomainModel() }
28 | }
29 |
30 | fun List.toEntityList(): List {
31 | return map { it.mapFromDomainModel() }
32 | }
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/local/WeatherDataStore.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.local
2 |
3 | import android.content.Context
4 | import androidx.datastore.core.DataStore
5 | import androidx.datastore.preferences.core.Preferences
6 | import androidx.datastore.preferences.core.booleanPreferencesKey
7 | import androidx.datastore.preferences.core.edit
8 | import androidx.datastore.preferences.core.emptyPreferences
9 | import androidx.datastore.preferences.core.stringPreferencesKey
10 | import androidx.datastore.preferences.preferencesDataStore
11 | import dagger.hilt.android.qualifiers.ApplicationContext
12 | import kotlinx.coroutines.flow.Flow
13 | import kotlinx.coroutines.flow.catch
14 | import kotlinx.coroutines.flow.distinctUntilChanged
15 | import kotlinx.coroutines.flow.map
16 | import java.io.IOException
17 | import javax.inject.Inject
18 | import javax.inject.Singleton
19 |
20 |
21 | object PREFS {
22 |
23 | val CITY_KEY = stringPreferencesKey("CITY_KEY")
24 | val DARK_MODE_KEY = booleanPreferencesKey("DARK_MODE")
25 | }
26 |
27 | @Singleton
28 | class WeatherDataStore @Inject constructor(@ApplicationContext context: Context) {
29 |
30 | private val Context.dataStore: DataStore by preferencesDataStore(name = "WeatherAppDS")
31 | private val dataStore = context.dataStore
32 |
33 | //city prefs
34 | suspend fun setCityPrefs(location: String) {
35 | dataStore.edit { pref ->
36 | pref[PREFS.CITY_KEY] = location
37 | }
38 | }
39 |
40 | fun getCityPrefs(): Flow = dataStore.data.distinctUntilChanged()
41 | .catch { exception ->
42 | if (exception is IOException) {
43 | emit(emptyPreferences())
44 | } else {
45 | throw exception
46 | }
47 | }
48 | .map { pref ->
49 | val location = pref[PREFS.CITY_KEY] ?: "Cairo, Egypt-127164"
50 | location
51 | }
52 |
53 | //dark mode prefs
54 | suspend fun setDarkThemePrefs(isDarkTheme: Boolean) {
55 | dataStore.edit { pref ->
56 | pref[PREFS.DARK_MODE_KEY] = isDarkTheme
57 | }
58 | }
59 |
60 | fun getDarkThemePrefs(): Flow = dataStore.data.distinctUntilChanged()
61 | .catch { exception ->
62 | if (exception is IOException) {
63 | emit(emptyPreferences())
64 | } else {
65 | throw exception
66 | }
67 | }
68 | .map { pref ->
69 | val onboard = pref[PREFS.DARK_MODE_KEY] ?: false
70 | onboard
71 | }
72 |
73 |
74 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/remote/CityDtoMapper.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.remote
2 |
3 |
4 | import com.weather.app.data.data_source.remote.response.AdministrativeArea
5 | import com.weather.app.data.data_source.remote.response.CityDataDTO
6 | import com.weather.app.data.data_source.remote.response.Country
7 | import com.weather.app.domain.model.City
8 |
9 |
10 | fun CityDataDTO.mapToDomainModel(): City {
11 | return City(
12 | id = key,
13 | localizedName = localizedName,
14 | country = country.localizedName,
15 | administrativeArea = administrativeArea.localizedName
16 | )
17 | }
18 |
19 | fun City.mapFromDomainModel(): CityDataDTO {
20 | return CityDataDTO(
21 | key = id,
22 | localizedName = localizedName,
23 | country = Country(localizedName = country),
24 | administrativeArea = AdministrativeArea(localizedName = administrativeArea)
25 | )
26 | }
27 |
28 | fun List.fromEntityList(): List {
29 | return map { it.mapToDomainModel() }
30 | }
31 |
32 | fun List.toEntityList(): List {
33 | return map { it.mapFromDomainModel() }
34 | }
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/remote/RetrofitService.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.remote
2 |
3 | import com.weather.app.data.data_source.remote.response.CityDataDTO
4 | import com.weather.app.data.data_source.remote.response.DailyForecastResponse
5 | import com.weather.app.data.data_source.remote.response.HourlyForecastData
6 | import com.weather.app.data.data_source.remote.response.WeatherData
7 | import retrofit2.http.GET
8 | import retrofit2.http.Path
9 | import retrofit2.http.Query
10 |
11 | const val API_KEY = "hNUBVNitjctSGngA0yAbbGVyjY4QBljs"
12 |
13 | interface RetrofitService {
14 |
15 | @GET("locations/v1/cities/autocomplete")
16 | suspend fun autoCompleteSearch(
17 | @Query("apikey") apiKey: String = API_KEY,
18 | @Query("q") q: String = "",
19 | ): List
20 |
21 | @GET("currentconditions/v1/{locationId}")
22 | suspend fun currentConditions(
23 | @Path("locationId") locationId: String = "",
24 | @Query("apikey") apiKey: String = API_KEY,
25 | ): List
26 |
27 | @GET("forecasts/v1/hourly/12hour/{cityId}")
28 | suspend fun getHourlyForecastByCityCode(
29 | @Path("cityId") cityId: String,
30 | @Query("apikey") apikey: String = API_KEY
31 | ): List
32 |
33 |
34 | @GET("forecasts/v1/daily/5day/{cityId}")
35 | suspend fun getDailyForecastByCityCode(
36 | @Path("cityId") cityId: String,
37 | @Query("apikey") apikey: String = API_KEY
38 | ): DailyForecastResponse
39 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/remote/response/CurrentConditionsResponse.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.remote.response
2 |
3 | import android.os.Parcelable
4 | import com.squareup.moshi.Json
5 | import com.squareup.moshi.JsonClass
6 | import kotlinx.parcelize.Parcelize
7 |
8 |
9 | @JsonClass(generateAdapter = true)
10 | @Parcelize
11 | data class WeatherData(
12 | @Json(name = "LocalObservationDateTime")
13 | val localObservationDateTime: String,
14 | @Json(name = "EpochTime")
15 | val epochTime: Long,
16 | @Json(name = "WeatherText")
17 | val weatherText: String,
18 | @Json(name = "WeatherIcon")
19 | val weatherIcon: Int,
20 | @Json(name = "HasPrecipitation")
21 | val hasPrecipitation: Boolean,
22 | @Json(name = "PrecipitationType")
23 | val precipitationType: String?,
24 | @Json(name = "IsDayTime")
25 | val isDayTime: Boolean,
26 | @Json(name = "Temperature")
27 | val temperature: Temperature,
28 | @Json(name = "MobileLink")
29 | val mobileLink: String,
30 | @Json(name = "Link")
31 | val link: String
32 | ) : Parcelable
33 |
34 | @JsonClass(generateAdapter = true)
35 | @Parcelize
36 | data class Temperature(
37 | @Json(name = "Metric")
38 | val metric: TemperatureUnit,
39 | @Json(name = "Imperial")
40 | val imperial: TemperatureUnit
41 | ) : Parcelable
42 |
43 | @JsonClass(generateAdapter = true)
44 | @Parcelize
45 | data class TemperatureUnit(
46 | @Json(name = "Value")
47 | val value: Double,
48 | @Json(name = "Unit")
49 | val unit: String,
50 | @Json(name = "UnitType")
51 | val unitType: Int
52 | ) : Parcelable
53 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/remote/response/DailyForecastResponse.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.remote.response
2 |
3 | import android.os.Parcelable
4 | import com.squareup.moshi.Json
5 | import com.squareup.moshi.JsonClass
6 | import kotlinx.parcelize.Parcelize
7 |
8 | @JsonClass(generateAdapter = true)
9 | @Parcelize
10 | data class DailyForecastResponse(
11 | @Json(name = "DailyForecasts")
12 | val dailyForecasts: List
13 | ) : Parcelable
14 |
15 | @JsonClass(generateAdapter = true)
16 | @Parcelize
17 | data class DailyForecastData(
18 | @Json(name = "Date")
19 | val date: String,
20 | @Json(name = "Temperature")
21 | val temperature: ForecastTemperature,
22 | @Json(name = "Day")
23 | val day: Day,
24 | @Json(name = "Link")
25 | val link: String
26 | ) : Parcelable
27 |
28 | @JsonClass(generateAdapter = true)
29 | @Parcelize
30 | data class ForecastTemperature(
31 | @Json(name = "Minimum")
32 | val minimum: Minimum,
33 | @Json(name = "Maximum")
34 | val maximum: Maximum
35 | ) : Parcelable
36 |
37 | @JsonClass(generateAdapter = true)
38 | @Parcelize
39 | data class Minimum(
40 | @Json(name = "Value")
41 | val value: Int,
42 | @Json(name = "Unit")
43 | val unit: String
44 | ) : Parcelable
45 |
46 | @JsonClass(generateAdapter = true)
47 | @Parcelize
48 | data class Maximum(
49 | @Json(name = "Value")
50 | val value: Int,
51 | @Json(name = "Unit")
52 | val unit: String
53 | ) : Parcelable
54 |
55 | @JsonClass(generateAdapter = true)
56 | @Parcelize
57 | data class Day(
58 | @Json(name = "Icon")
59 | val icon: Int,
60 | @Json(name = "IconPhrase")
61 | val iconPhrase: String
62 | ) : Parcelable
63 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/remote/response/HourlyForecastData.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.remote.response
2 |
3 | import android.os.Parcelable
4 | import com.squareup.moshi.Json
5 | import com.squareup.moshi.JsonClass
6 | import kotlinx.parcelize.Parcelize
7 |
8 |
9 | @JsonClass(generateAdapter = true)
10 | @Parcelize
11 | data class HourlyForecastData(
12 | @Json(name = "DateTime")
13 | val dateTime: String,
14 | @Json(name = "IconPhrase")
15 | val iconPhrase: String,
16 | @Json(name = "WeatherIcon")
17 | val weatherIcon: Int,
18 | @Json(name = "Temperature")
19 | val temperature: HourlyTemperature,
20 | @Json(name = "Link")
21 | val link: String
22 | ) : Parcelable
23 |
24 | @JsonClass(generateAdapter = true)
25 | @Parcelize
26 | data class HourlyTemperature(
27 | @Json(name = "Value")
28 | val value: Int,
29 | @Json(name = "Unit")
30 | val unit: String
31 | ) : Parcelable
32 |
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/data_source/remote/response/SearchResponse.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.data_source.remote.response
2 |
3 | import android.os.Parcelable
4 | import com.squareup.moshi.Json
5 | import com.squareup.moshi.JsonClass
6 | import kotlinx.parcelize.Parcelize
7 |
8 |
9 | @JsonClass(generateAdapter = true)
10 | @Parcelize
11 | data class CityDataDTO(
12 | @Json(name = "Version")
13 | val version: Int? = null,
14 | @Json(name = "Type")
15 | val type: String? = null,
16 | @Json(name = "Rank")
17 | val rank: Int? = null,
18 | @Json(name = "Key")
19 | val key: String,
20 | @Json(name = "LocalizedName")
21 | val localizedName: String,
22 | @Json(name = "Country")
23 | val country: Country,
24 | @Json(name = "AdministrativeArea")
25 | val administrativeArea: AdministrativeArea
26 | ) : Parcelable
27 |
28 | @JsonClass(generateAdapter = true)
29 | @Parcelize
30 | data class Country(
31 | @Json(name = "ID")
32 | val id: String? = null,
33 | @Json(name = "LocalizedName")
34 | val localizedName: String
35 | ) : Parcelable
36 |
37 | @JsonClass(generateAdapter = true)
38 | @Parcelize
39 | data class AdministrativeArea(
40 | @Json(name = "ID")
41 | val id: String? = null,
42 | @Json(name = "LocalizedName")
43 | val localizedName: String
44 | ) : Parcelable
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/data/repository/AppRepositoryImpl.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.data.repository
2 |
3 | import com.weather.app.data.data_source.local.AppDao
4 | import com.weather.app.data.data_source.local.CityEntity
5 | import com.weather.app.data.data_source.local.mapFromDomainModel
6 | import com.weather.app.data.data_source.remote.RetrofitService
7 | import com.weather.app.data.data_source.remote.fromEntityList
8 | import com.weather.app.data.data_source.remote.response.DailyForecastData
9 | import com.weather.app.data.data_source.remote.response.HourlyForecastData
10 | import com.weather.app.data.data_source.remote.response.WeatherData
11 | import com.weather.app.domain.DataState
12 | import com.weather.app.domain.model.City
13 | import com.weather.app.domain.repository.AppRepository
14 | import kotlinx.coroutines.flow.Flow
15 | import kotlinx.coroutines.flow.flow
16 |
17 | class AppRepositoryImpl(
18 | private val dao: AppDao,
19 | private val retrofitService: RetrofitService,
20 | ) : AppRepository {
21 |
22 | override fun getSearchResults(query: String): Flow>> = flow {
23 | try {
24 | emit(DataState.loading())
25 | val response = retrofitService.autoCompleteSearch(q = query)
26 | emit(DataState.success(response.fromEntityList()))
27 | } catch (e: Exception) {
28 | emit(DataState.error(e.message ?: "Unknown error"))
29 | }
30 | }
31 |
32 | override suspend fun addCityOffline(city: City) {
33 | dao.insertEntity(city.mapFromDomainModel())
34 | }
35 |
36 | override suspend fun deleteCity(city: City) {
37 | dao.deleteEntity(city.mapFromDomainModel())
38 | }
39 |
40 |
41 | override suspend fun getCities(): Flow> {
42 | return dao.getEntities()
43 | }
44 |
45 | override suspend fun getCurrentConditions(locationId: String): Flow>> =
46 | flow {
47 | try {
48 | emit(DataState.loading())
49 | val response = retrofitService.currentConditions(locationId)
50 | emit(DataState.success(response))
51 | } catch (e: Exception) {
52 | emit(DataState.error(e.message ?: "Unknown error"))
53 | }
54 | }
55 |
56 | override suspend fun getHourlyForecasts(locationId: String): Flow>> =
57 | flow {
58 | try {
59 | emit(DataState.loading())
60 | val response = retrofitService.getHourlyForecastByCityCode(locationId)
61 | emit(DataState.success(response))
62 | } catch (e: Exception) {
63 | emit(DataState.error(e.message ?: "Unknown error"))
64 | }
65 | }
66 |
67 | override suspend fun getDailyForecasts(locationId: String): Flow>> =
68 | flow {
69 | try {
70 | emit(DataState.loading())
71 | val response = retrofitService.getDailyForecastByCityCode(locationId)
72 | emit(DataState.success(response.dailyForecasts))
73 | } catch (e: Exception) {
74 | emit(DataState.error(e.message ?: "Unknown error"))
75 | }
76 | }
77 |
78 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/di/AppModule.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.di
2 |
3 | import com.weather.app.domain.repository.AppRepository
4 | import com.weather.app.domain.use_case.*
5 | import dagger.Module
6 | import dagger.Provides
7 | import dagger.hilt.InstallIn
8 | import dagger.hilt.components.SingletonComponent
9 | import javax.inject.Singleton
10 |
11 | @Module
12 | @InstallIn(SingletonComponent::class)
13 | object AppModule {
14 |
15 | @Provides
16 | @Singleton
17 | fun provideAppUseCases(repository: AppRepository): AppUseCases {
18 | return AppUseCases(
19 | getSearchResults = GetSearchResults(repository),
20 | getCurrentConditions = GetCurrentConditions(repository),
21 | addCityOffline = AddCityOffline(repository),
22 | getCities = GetCities(repository),
23 | deleteCity = DeleteCity(repository),
24 | hourlyForecasts = GetHourlyForecasts(repository),
25 | dailyForecasts = GetDailyForecasts(repository)
26 | )
27 | }
28 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/di/LocalModule.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.di
2 |
3 | import android.app.Application
4 | import androidx.room.Room
5 | import com.weather.app.data.data_source.local.AppDatabase
6 | import com.weather.app.data.data_source.remote.RetrofitService
7 | import com.weather.app.data.repository.AppRepositoryImpl
8 | import com.weather.app.domain.repository.AppRepository
9 | import dagger.Module
10 | import dagger.Provides
11 | import dagger.hilt.InstallIn
12 | import dagger.hilt.components.SingletonComponent
13 | import javax.inject.Singleton
14 |
15 | @Module
16 | @InstallIn(SingletonComponent::class)
17 | object LocalModule {
18 |
19 | @Provides
20 | @Singleton
21 | fun provideAppDatabase(app: Application): AppDatabase {
22 | return Room.databaseBuilder(
23 | app,
24 | AppDatabase::class.java,
25 | AppDatabase.DATABASE_NAME
26 | ).build()
27 | }
28 |
29 | @Provides
30 | @Singleton
31 | fun provideEntityRepository(
32 | db: AppDatabase,
33 | retrofitService: RetrofitService,
34 | ): AppRepository {
35 | return AppRepositoryImpl(db.appDao, retrofitService)
36 | }
37 |
38 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/di/NetworkModule.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.di
2 |
3 |
4 | import com.squareup.moshi.Moshi
5 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
6 | import com.weather.app.data.data_source.remote.RetrofitService
7 | import com.weather.app.util.BASE_URL
8 | import dagger.Module
9 | import dagger.Provides
10 | import dagger.hilt.InstallIn
11 | import dagger.hilt.components.SingletonComponent
12 | import okhttp3.OkHttpClient
13 | import okhttp3.logging.HttpLoggingInterceptor
14 | import retrofit2.Retrofit
15 | import retrofit2.converter.moshi.MoshiConverterFactory
16 | import javax.inject.Singleton
17 |
18 | @Module
19 | @InstallIn(SingletonComponent::class)
20 | object NetworkModule {
21 |
22 | @Provides
23 | @Singleton
24 | fun provideOkHttpClient(): OkHttpClient {
25 | return OkHttpClient.Builder().apply {
26 | val loggingInterceptor = HttpLoggingInterceptor()
27 | loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
28 | addInterceptor(loggingInterceptor)
29 | }.build()
30 | }
31 |
32 | @Singleton
33 | @Provides
34 | fun providesMoshi() = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
35 |
36 | @Singleton
37 | @Provides
38 | fun provideService(okHttpClient: OkHttpClient, mosh: Moshi): RetrofitService {
39 | return Retrofit.Builder()
40 | .baseUrl(BASE_URL)
41 | .addConverterFactory(MoshiConverterFactory.create(mosh))
42 | .client(okHttpClient)
43 | .build()
44 | .create(RetrofitService::class.java)
45 | }
46 |
47 |
48 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/DataState.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain
2 |
3 | data class DataState(
4 | val data: T? = null,
5 | val error: String? = null,
6 | val loading: Boolean = false
7 | ) {
8 |
9 | companion object {
10 |
11 | fun success(data: T): DataState {
12 | return DataState(data = data)
13 | }
14 |
15 | fun error(message: String): DataState {
16 | return DataState(error = message)
17 | }
18 |
19 | fun loading(): DataState = DataState(loading = true)
20 | }
21 | }
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/model/City.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.model
2 |
3 |
4 | data class City(
5 | val id: String,
6 | val localizedName: String,
7 | val country: String,
8 | val administrativeArea: String,
9 | val isSelected: Boolean = false
10 | )
11 |
12 | class InvalidDataException(message: String) : Exception(message)
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/repository/AppRepository.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.repository
2 |
3 | import com.weather.app.data.data_source.local.CityEntity
4 | import com.weather.app.data.data_source.remote.response.DailyForecastData
5 | import com.weather.app.data.data_source.remote.response.HourlyForecastData
6 | import com.weather.app.data.data_source.remote.response.WeatherData
7 | import com.weather.app.domain.DataState
8 | import com.weather.app.domain.model.City
9 | import kotlinx.coroutines.flow.Flow
10 |
11 | interface AppRepository {
12 |
13 | fun getSearchResults(query: String): Flow>>
14 | suspend fun addCityOffline(city: City)
15 | suspend fun deleteCity(city: City)
16 | suspend fun getCities(): Flow>
17 | suspend fun getCurrentConditions(locationId: String): Flow>>
18 | suspend fun getHourlyForecasts(locationId: String): Flow>>
19 | suspend fun getDailyForecasts(locationId: String): Flow>>
20 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/use_case/AddCityOffline.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.use_case
2 |
3 | import com.weather.app.domain.model.City
4 | import com.weather.app.domain.repository.AppRepository
5 |
6 | class AddCityOffline(
7 | private val repository: AppRepository,
8 | ) {
9 | suspend operator fun invoke(city: City) =
10 | repository.addCityOffline(city)
11 |
12 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/use_case/AppUseCases.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.use_case
2 |
3 | data class AppUseCases(
4 | val getSearchResults: GetSearchResults,
5 | val addCityOffline: AddCityOffline,
6 | val deleteCity: DeleteCity,
7 | val getCities: GetCities,
8 | val getCurrentConditions: GetCurrentConditions,
9 | val hourlyForecasts: GetHourlyForecasts,
10 | val dailyForecasts: GetDailyForecasts,
11 | )
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/use_case/DeleteCity.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.use_case
2 |
3 | import com.weather.app.domain.model.City
4 | import com.weather.app.domain.repository.AppRepository
5 |
6 | class DeleteCity(
7 | private val repository: AppRepository,
8 | ) {
9 | suspend operator fun invoke(city: City) =
10 | repository.deleteCity(city)
11 |
12 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/use_case/GetCities.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.use_case
2 |
3 | import com.weather.app.domain.repository.AppRepository
4 |
5 | class GetCities(
6 | private val repository: AppRepository,
7 | ) {
8 | suspend operator fun invoke() =
9 | repository.getCities()
10 |
11 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/use_case/GetCurrentConditions.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.use_case
2 |
3 | import com.weather.app.data.data_source.remote.response.WeatherData
4 | import com.weather.app.domain.DataState
5 | import com.weather.app.domain.repository.AppRepository
6 | import kotlinx.coroutines.flow.Flow
7 |
8 | class GetCurrentConditions(
9 | private val repository: AppRepository
10 | ) {
11 |
12 | suspend operator fun invoke(locationId: String): Flow>> {
13 | return repository.getCurrentConditions(locationId)
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/use_case/GetDailyForecasts.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.use_case
2 |
3 | import com.weather.app.data.data_source.remote.response.DailyForecastData
4 | import com.weather.app.domain.DataState
5 | import com.weather.app.domain.repository.AppRepository
6 | import kotlinx.coroutines.flow.Flow
7 |
8 | class GetDailyForecasts(
9 | private val repository: AppRepository
10 | ) {
11 |
12 | suspend operator fun invoke(locationId: String): Flow>> {
13 | return repository.getDailyForecasts(locationId)
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/use_case/GetHourlyForecasts.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.use_case
2 |
3 | import com.weather.app.data.data_source.remote.response.HourlyForecastData
4 | import com.weather.app.domain.DataState
5 | import com.weather.app.domain.repository.AppRepository
6 | import kotlinx.coroutines.flow.Flow
7 |
8 | class GetHourlyForecasts(
9 | private val repository: AppRepository
10 | ) {
11 |
12 | suspend operator fun invoke(locationId: String): Flow>> {
13 | return repository.getHourlyForecasts(locationId)
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/domain/use_case/GetSearchResults.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.domain.use_case
2 |
3 | import com.weather.app.domain.DataState
4 | import com.weather.app.domain.model.City
5 | import com.weather.app.domain.repository.AppRepository
6 | import kotlinx.coroutines.flow.Flow
7 |
8 | class GetSearchResults(
9 | private val repository: AppRepository,
10 | ) {
11 | operator fun invoke(query: String): Flow>> =
12 | repository.getSearchResults(query)
13 |
14 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/extension/DateExtension.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.extension
2 |
3 | import java.text.SimpleDateFormat
4 | import java.util.Calendar
5 | import java.util.Date
6 | import java.util.Locale
7 |
8 | fun Date.toFormattedDateString(): String {
9 | val sdf = SimpleDateFormat("EEEE, LLLL dd", Locale.getDefault())
10 | return sdf.format(this)
11 | }
12 |
13 | fun Date.toFormattedMonthDateString(): String {
14 | val sdf = SimpleDateFormat("MMMM dd", Locale.getDefault())
15 | return sdf.format(this)
16 | }
17 |
18 | fun Date.toFormattedDateShortString(): String {
19 | val sdf = SimpleDateFormat("dd", Locale.getDefault())
20 | return sdf.format(this)
21 | }
22 |
23 | fun Long.toFormattedDateString(): String {
24 | val sdf = SimpleDateFormat("EEEE, LLLL dd", Locale.getDefault())
25 | return sdf.format(this)
26 | }
27 |
28 | fun Long.toFormattedTimeString(): String {
29 | val timeFormat = SimpleDateFormat("hh:mm a", Locale.getDefault())
30 | return timeFormat.format(this)
31 | }
32 |
33 | fun Date.hasPassed(): Boolean {
34 | val calendar = Calendar.getInstance()
35 | calendar.add(Calendar.SECOND, -1)
36 | val oneSecondAgo = calendar.time
37 | return time < oneSecondAgo.time
38 | }
39 |
40 | fun String.convertHourlyTimestamp(): String {
41 | val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH)
42 | val date = inputFormat.parse(this)
43 |
44 | val calendar = Calendar.getInstance()
45 | calendar.time = date
46 |
47 | val hour = calendar.get(Calendar.HOUR_OF_DAY)
48 | val minute = calendar.get(Calendar.MINUTE)
49 |
50 | val isAM = hour < 12
51 | val formattedHour = if (hour > 12) hour - 12 else hour
52 | val formattedMinute = String.format("%02d", minute)
53 |
54 | val period = if (isAM) "AM" else "PM"
55 |
56 | return "$formattedHour:$formattedMinute $period"
57 | }
58 |
59 | fun String.getDayOfWeek(): String {
60 | val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.US)
61 | val date = inputFormat.parse(this)
62 | val calendar = Calendar.getInstance()
63 | calendar.time = date
64 | val dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)
65 | return when (dayOfWeek) {
66 | Calendar.SUNDAY -> "Sunday"
67 | Calendar.MONDAY -> "Monday"
68 | Calendar.TUESDAY -> "Tuesday"
69 | Calendar.WEDNESDAY -> "Wednesday"
70 | Calendar.THURSDAY -> "Thursday"
71 | Calendar.FRIDAY -> "Friday"
72 | Calendar.SATURDAY -> "Saturday"
73 | else -> ""
74 | }
75 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/extension/WeatherIcons.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.extension
2 |
3 | import com.weather.app.R
4 |
5 | fun Int.getDrawable(): Int {
6 | return when (this) {
7 | 1, 2, 3 -> R.drawable.sunny
8 | 4, 5, 6, 7, 20, 21, 22, 23, 24 -> R.drawable.cloudy
9 | 8, 11, 30, 31, 32, 19 -> R.drawable.clouds
10 | 12, 18, 25, 26, 29 -> R.drawable.rainy
11 | 13, 14 -> R.drawable.partly_cloudy
12 | 15, 16, 17, 39, 40, 41, 42 -> R.drawable.rain_lightning
13 | 33, 34, 35 -> R.drawable.sunny_night
14 | 36, 37, 38, 43, 44 -> R.drawable.cloudy_night
15 | else -> {
16 | R.drawable.ic_launcher_foreground
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/navigation/AppLevelNavigation.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.navigation
2 |
3 | import androidx.compose.material.icons.Icons
4 | import androidx.compose.material.icons.filled.Home
5 | import androidx.compose.material.icons.filled.Settings
6 | import androidx.compose.material.icons.filled.Star
7 | import androidx.compose.material.icons.outlined.Home
8 | import androidx.compose.material.icons.outlined.Settings
9 | import androidx.compose.material.icons.outlined.Star
10 | import androidx.compose.ui.graphics.vector.ImageVector
11 | import androidx.navigation.NavGraph.Companion.findStartDestination
12 | import androidx.navigation.NavHostController
13 | import com.weather.app.R
14 | import com.weather.app.presentation.home_screen.navigation.HomeScreenDestination
15 | import com.weather.app.presentation.settings_screen.navigation.SettingsScreenDestination
16 | import com.weather.app.presentation.weather_animation_screen.navigation.AnimationScreenDestination
17 |
18 | class AppTopLevelNavigation(private val navController: NavHostController) {
19 |
20 | fun navigateTo(destination: TopLevelDestination) {
21 | navController.navigate(destination.route) {
22 | // Pop up to the start destination of the graph to
23 | // avoid building up a large stack of destinations
24 | // on the back stack as users select items
25 | popUpTo(navController.graph.findStartDestination().id) {
26 | saveState = true
27 | }
28 | // Avoid multiple copies of the same destination when
29 | // reselecting the same item
30 | launchSingleTop = true
31 | // Restore state when reselecting a previously selected item
32 | restoreState = true
33 | }
34 | }
35 | }
36 |
37 | data class TopLevelDestination(
38 | val route: String,
39 | val selectedIcon: ImageVector,
40 | val unselectedIcon: ImageVector,
41 | val iconTextId: Int
42 | )
43 |
44 | val TOP_LEVEL_DESTINATIONS = listOf(
45 | TopLevelDestination(
46 | route = HomeScreenDestination.route,
47 | selectedIcon = Icons.Filled.Home,
48 | unselectedIcon = Icons.Outlined.Home,
49 | iconTextId = R.string.home
50 | ),
51 | TopLevelDestination(
52 | route = AnimationScreenDestination.route,
53 | selectedIcon = Icons.Filled.Star,
54 | unselectedIcon = Icons.Outlined.Star,
55 | iconTextId = R.string.animation
56 | ),
57 | TopLevelDestination(
58 | route = SettingsScreenDestination.route,
59 | selectedIcon = Icons.Filled.Settings,
60 | unselectedIcon = Icons.Outlined.Settings,
61 | iconTextId = R.string.settings
62 | ),
63 | )
64 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/navigation/AppNavigationDestination.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.navigation
2 |
3 | /**
4 | * Interface for describing the Now in Android navigation destinations
5 | */
6 |
7 | interface AppNavigationDestination {
8 | /**
9 | * Defines a specific route this destination belongs to.
10 | * Route is a String that defines the path to your composable.
11 | * You can think of it as an implicit deep link that leads to a specific destination.
12 | * Each destination should have a unique route.
13 | */
14 | val route: String
15 |
16 | /**
17 | * Defines a specific destination ID.
18 | * This is needed when using nested graphs via the navigation DLS, to differentiate a specific
19 | * destination's route from the route of the entire nested graph it belongs to.
20 | */
21 | val destination: String
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/navigation/NavigateSingleTop.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.navigation
2 |
3 | import androidx.navigation.NavHostController
4 |
5 | fun NavHostController.navigateSingleTop(route: String) {
6 | this.navigate(route) {
7 | popUpTo(route)
8 | launchSingleTop = true
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.compose.animation.ExperimentalAnimationApi
7 | import androidx.compose.runtime.LaunchedEffect
8 | import androidx.compose.runtime.getValue
9 | import androidx.compose.runtime.mutableStateOf
10 | import androidx.compose.runtime.remember
11 | import androidx.compose.runtime.setValue
12 | import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
13 | import com.weather.app.data.data_source.local.WeatherDataStore
14 | import com.weather.app.presentation.components.DisposableEffectWithLifeCycle
15 | import com.weather.app.presentation.navigation.MyApp
16 | import com.weather.app.util.ConnectivityManager
17 | import dagger.hilt.android.AndroidEntryPoint
18 | import javax.inject.Inject
19 |
20 | @AndroidEntryPoint
21 | class MainActivity : ComponentActivity() {
22 |
23 | @Inject
24 | lateinit var connectivityManager: ConnectivityManager
25 |
26 | @Inject
27 | lateinit var dataStore: WeatherDataStore
28 |
29 | @ExperimentalAnimationApi
30 | override fun onCreate(savedInstanceState: Bundle?) {
31 | // Handle the splash screen transition.
32 | installSplashScreen()
33 | super.onCreate(savedInstanceState)
34 | setContent {
35 | DisposableEffectWithLifeCycle(
36 | onStart = {
37 | connectivityManager.registerConnectionObserver(this)
38 | },
39 | onDestroy = {
40 | connectivityManager.registerConnectionObserver(this)
41 | }
42 | )
43 | var darkThemeState by remember { mutableStateOf(false) }
44 | LaunchedEffect(key1 = true) {
45 | dataStore.getDarkThemePrefs().collect {
46 | darkThemeState = it
47 | }
48 | }
49 | MyApp(
50 | isNetworkAvailable = connectivityManager.isNetworkAvailable.value,
51 | isDarkTheme = darkThemeState
52 | )
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/components/CityItem.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.components
2 |
3 | import androidx.compose.foundation.Image
4 | import androidx.compose.foundation.background
5 | import androidx.compose.foundation.clickable
6 | import androidx.compose.foundation.layout.Arrangement
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.Row
9 | import androidx.compose.foundation.layout.Spacer
10 | import androidx.compose.foundation.layout.fillMaxWidth
11 | import androidx.compose.foundation.layout.padding
12 | import androidx.compose.foundation.layout.size
13 | import androidx.compose.foundation.layout.width
14 | import androidx.compose.material.icons.Icons
15 | import androidx.compose.material.icons.filled.LocationOn
16 | import androidx.compose.material3.MaterialTheme
17 | import androidx.compose.material3.Text
18 | import androidx.compose.runtime.Composable
19 | import androidx.compose.ui.Alignment
20 | import androidx.compose.ui.Modifier
21 | import androidx.compose.ui.unit.dp
22 | import com.weather.app.domain.model.City
23 |
24 |
25 | @Composable
26 | fun CityItem(city: City, onClick: (City) -> Unit) {
27 | Row(verticalAlignment = Alignment.CenterVertically,
28 | modifier = Modifier
29 | .fillMaxWidth()
30 | .padding(8.dp)
31 | .background(MaterialTheme.colorScheme.surface)
32 | .clickable { onClick(city) }
33 | ) {
34 | Column(
35 | verticalArrangement = Arrangement.Center,
36 | modifier = Modifier
37 | .weight(1f)
38 | .padding(start = 16.dp, top = 8.dp, bottom = 8.dp, end = 16.dp)
39 | ) {
40 | Text(text = city.localizedName, style = MaterialTheme.typography.titleMedium)
41 | Text(text = city.country, style = MaterialTheme.typography.titleSmall)
42 | }
43 | Spacer(modifier = Modifier.width(16.dp))
44 | Image(
45 | imageVector = Icons.Default.LocationOn,
46 | contentDescription = null,
47 | modifier = Modifier
48 | .size(24.dp)
49 | )
50 | }
51 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/components/ConnectivityMonitor.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.components
2 |
3 | import androidx.compose.foundation.layout.Column
4 | import androidx.compose.foundation.layout.fillMaxWidth
5 | import androidx.compose.foundation.layout.padding
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.Text
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.ui.Alignment
10 | import androidx.compose.ui.Modifier
11 | import androidx.compose.ui.unit.dp
12 |
13 | @Composable
14 | fun NoConnectionAvailable() {
15 |
16 | Column(modifier = Modifier.fillMaxWidth()) {
17 | Text(
18 | "No network connection",
19 | modifier = Modifier
20 | .align(Alignment.CenterHorizontally)
21 | .padding(8.dp),
22 | style = MaterialTheme.typography.titleMedium,
23 | color = MaterialTheme.colorScheme.onBackground
24 | )
25 | }
26 |
27 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/components/DailyForecastItem.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.components
2 |
3 | import androidx.compose.foundation.Image
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.Row
7 | import androidx.compose.foundation.layout.Spacer
8 | import androidx.compose.foundation.layout.fillMaxWidth
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.foundation.layout.size
11 | import androidx.compose.foundation.layout.width
12 | import androidx.compose.foundation.layout.wrapContentHeight
13 | import androidx.compose.foundation.shape.RoundedCornerShape
14 | import androidx.compose.material3.Card
15 | import androidx.compose.material3.CardDefaults
16 |
17 | import androidx.compose.material3.MaterialTheme
18 | import androidx.compose.material3.Text
19 | import androidx.compose.runtime.Composable
20 | import androidx.compose.ui.Modifier
21 | import androidx.compose.ui.res.painterResource
22 | import androidx.compose.ui.unit.dp
23 | import com.weather.app.data.data_source.remote.response.DailyForecastData
24 | import com.weather.app.extension.getDayOfWeek
25 | import com.weather.app.extension.getDrawable
26 |
27 |
28 | @Composable
29 | fun DailyForecastItem(
30 | dailyForecastData: DailyForecastData,
31 | onClick: (DailyForecastData) -> Unit
32 | ) {
33 | Card(
34 | colors = CardDefaults.cardColors(
35 | containerColor = MaterialTheme.colorScheme.surface,
36 | ),
37 | shape = RoundedCornerShape(10.dp),
38 | modifier = Modifier.padding(top = 16.dp, start = 16.dp, end = 16.dp)
39 | ) {
40 | Row(
41 | modifier = Modifier
42 | .fillMaxWidth()
43 | .wrapContentHeight()
44 | .padding(10.dp)
45 | .clickable { onClick(dailyForecastData) }
46 | ) {
47 | Image(
48 | painter = painterResource(id = dailyForecastData.day.icon.getDrawable()),
49 | contentDescription = null,
50 | modifier = Modifier
51 | .size(35.dp)
52 | )
53 |
54 | Spacer(modifier = Modifier.width(10.dp))
55 | Column {
56 | Text(
57 | text = dailyForecastData.day.iconPhrase,
58 | style = MaterialTheme.typography.titleSmall, maxLines = 1
59 | )
60 | Text(
61 | text = dailyForecastData.date.getDayOfWeek(),
62 | style = MaterialTheme.typography.titleSmall, maxLines = 1
63 | )
64 | }
65 |
66 | Spacer(modifier = Modifier.weight(1f))
67 | Text(
68 | text = "${((dailyForecastData.temperature.maximum.value - 32) * 5 / 9)} / ${((dailyForecastData.temperature.minimum.value - 32) * 5 / 9)} °C",
69 | style = MaterialTheme.typography.titleSmall, maxLines = 1
70 | )
71 |
72 |
73 | }
74 |
75 | }
76 |
77 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/components/DisposableEffectWithLifeCycle.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.components
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.compose.runtime.DisposableEffect
5 | import androidx.compose.runtime.getValue
6 | import androidx.compose.runtime.rememberUpdatedState
7 | import androidx.compose.ui.platform.LocalLifecycleOwner
8 | import androidx.lifecycle.Lifecycle
9 | import androidx.lifecycle.LifecycleEventObserver
10 | import androidx.lifecycle.LifecycleOwner
11 |
12 | @Composable
13 | fun DisposableEffectWithLifeCycle(
14 | onStart: () -> Unit,
15 | onDestroy: () -> Unit,
16 | ) {
17 | // Safely update the current lambdas when a new one is provided
18 | val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current
19 |
20 | val currentOnStart by rememberUpdatedState(onStart)
21 | val currentOnDestroy by rememberUpdatedState(onDestroy)
22 |
23 | // If `lifecycleOwner` changes, dispose and reset the effect
24 | DisposableEffect(lifecycleOwner) {
25 | // Create an observer that triggers our remembered callbacks
26 | // for lifecycle events
27 | val observer = LifecycleEventObserver { _, event ->
28 | when (event) {
29 |
30 | Lifecycle.Event.ON_START -> {
31 | currentOnStart()
32 | }
33 |
34 | Lifecycle.Event.ON_DESTROY -> {
35 | currentOnDestroy()
36 | }
37 |
38 | else -> {}
39 | }
40 | }
41 |
42 | // Add the observer to the lifecycle
43 | lifecycleOwner.lifecycle.addObserver(observer)
44 |
45 | // When the effect leaves the Composition, remove the observer
46 | onDispose {
47 | lifecycleOwner.lifecycle.removeObserver(observer)
48 | }
49 | }
50 |
51 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/components/GenericDialog.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.components
2 |
3 | import androidx.compose.foundation.layout.Arrangement
4 | import androidx.compose.foundation.layout.Row
5 | import androidx.compose.foundation.layout.fillMaxWidth
6 | import androidx.compose.foundation.layout.padding
7 | import androidx.compose.material3.AlertDialog
8 | import androidx.compose.material3.Button
9 | import androidx.compose.material3.ButtonDefaults
10 | import androidx.compose.material3.MaterialTheme
11 | import androidx.compose.material3.Text
12 | import androidx.compose.runtime.Composable
13 | import androidx.compose.ui.Modifier
14 | import androidx.compose.ui.unit.dp
15 |
16 |
17 | @Composable
18 | fun GenericDialog(
19 | modifier: Modifier = Modifier,
20 | onDismiss: () -> Unit,
21 | title: String,
22 | description: String? = null,
23 | positiveAction: PositiveAction?,
24 | negativeAction: NegativeAction?,
25 | ) {
26 | AlertDialog(
27 | modifier = modifier,
28 | onDismissRequest = onDismiss,
29 | title = { Text(title) },
30 | text = {
31 | if (description != null) {
32 | Text(text = description)
33 | }
34 | },
35 | confirmButton = {
36 | Row(
37 | modifier = Modifier
38 | .fillMaxWidth()
39 | .padding(8.dp),
40 | horizontalArrangement = Arrangement.End,
41 | ) {
42 |
43 | if (positiveAction != null) {
44 | Button(
45 | modifier = Modifier.padding(end = 8.dp),
46 | onClick = positiveAction.onPositiveAction,
47 | ) {
48 | Text(text = positiveAction.positiveBtnTxt)
49 | }
50 | }
51 | }
52 | }, dismissButton = {
53 | if (negativeAction != null) {
54 | Button(
55 | modifier = Modifier.padding(end = 8.dp),
56 | colors = ButtonDefaults.buttonColors(MaterialTheme.colorScheme.onError),
57 | onClick = negativeAction.onNegativeAction
58 | ) {
59 | Text(text = negativeAction.negativeBtnTxt)
60 | }
61 | }
62 | }
63 | )
64 | }
65 |
66 | data class PositiveAction(
67 | val positiveBtnTxt: String,
68 | val onPositiveAction: () -> Unit,
69 | )
70 |
71 | data class NegativeAction(
72 | val negativeBtnTxt: String,
73 | val onNegativeAction: () -> Unit,
74 | )
75 |
76 | class GenericDialogInfo
77 | private constructor(builder: Builder) {
78 | val title: String
79 | val onDismiss: () -> Unit
80 | val description: String?
81 | val positiveAction: PositiveAction?
82 | val negativeAction: NegativeAction?
83 |
84 | init {
85 | if (builder.title == null) {
86 | throw Exception("GenericDialog title cannot be null.")
87 | }
88 | if (builder.onDismiss == null) {
89 | throw Exception("GenericDialog onDismiss function cannot be null.")
90 | }
91 | this.title = builder.title!!
92 | this.onDismiss = builder.onDismiss!!
93 | this.description = builder.description
94 | this.positiveAction = builder.positiveAction
95 | this.negativeAction = builder.negativeAction
96 |
97 | }
98 |
99 | class Builder {
100 | var title: String? = null
101 | private set
102 |
103 | var onDismiss: (() -> Unit)? = null
104 | private set
105 |
106 | var description: String? = null
107 | private set
108 |
109 | var positiveAction: PositiveAction? = null
110 | private set
111 |
112 | var negativeAction: NegativeAction? = null
113 | private set
114 |
115 | fun title(title: String): Builder {
116 | this.title = title
117 | return this
118 | }
119 |
120 | fun onDismiss(onDismiss: () -> Unit): Builder {
121 | this.onDismiss = onDismiss
122 | return this
123 | }
124 |
125 | fun description(
126 | description: String
127 | ): Builder {
128 | this.description = description
129 | return this
130 | }
131 |
132 | fun positive(
133 | positiveAction: PositiveAction?,
134 | ): Builder {
135 | this.positiveAction = positiveAction
136 | return this
137 | }
138 |
139 | fun negative(
140 | negativeAction: NegativeAction
141 | ): Builder {
142 | this.negativeAction = negativeAction
143 | return this
144 | }
145 |
146 | fun build() = GenericDialogInfo(this)
147 | }
148 |
149 | }
150 |
151 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/components/HourlyForecastItem.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.components
2 |
3 | import androidx.compose.foundation.Image
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.Spacer
7 | import androidx.compose.foundation.layout.height
8 | import androidx.compose.foundation.layout.padding
9 | import androidx.compose.foundation.layout.size
10 | import androidx.compose.foundation.layout.width
11 | import androidx.compose.foundation.shape.RoundedCornerShape
12 | import androidx.compose.material3.Card
13 | import androidx.compose.material3.CardDefaults
14 | import androidx.compose.material3.MaterialTheme
15 | import androidx.compose.material3.Text
16 | import androidx.compose.runtime.Composable
17 | import androidx.compose.ui.Alignment
18 | import androidx.compose.ui.Modifier
19 | import androidx.compose.ui.res.painterResource
20 | import androidx.compose.ui.tooling.preview.Preview
21 | import androidx.compose.ui.unit.dp
22 | import com.weather.app.data.data_source.remote.response.HourlyForecastData
23 | import com.weather.app.data.data_source.remote.response.HourlyTemperature
24 | import com.weather.app.extension.convertHourlyTimestamp
25 | import com.weather.app.extension.getDrawable
26 | import com.weather.app.theme.AppTheme
27 |
28 |
29 | @Composable
30 | fun HourlyForecastItem(
31 | hourlyForecastData: HourlyForecastData,
32 | onClick: (HourlyForecastData) -> Unit
33 | ) {
34 | Card(
35 | colors = CardDefaults.cardColors(
36 | containerColor = MaterialTheme.colorScheme.surface,
37 | ),
38 | shape = RoundedCornerShape(10.dp),
39 | modifier = Modifier.padding(end = 10.dp)
40 | ) {
41 | Column(horizontalAlignment = Alignment.CenterHorizontally,
42 | modifier = Modifier
43 | .width(80.dp)
44 | .padding(10.dp)
45 | .clickable { onClick(hourlyForecastData) }
46 | ) {
47 | Image(
48 | painter = painterResource(id = hourlyForecastData.weatherIcon.getDrawable()),
49 | contentDescription = null,
50 | modifier = Modifier
51 | .size(35.dp)
52 | )
53 |
54 | Spacer(modifier = Modifier.height(5.dp))
55 | Text(
56 |
57 | text = "${((hourlyForecastData.temperature.value - 32) * 5 / 9)}°",
58 | style = MaterialTheme.typography.titleSmall
59 | )
60 |
61 | Spacer(modifier = Modifier.height(5.dp))
62 | Text(
63 | text = hourlyForecastData.dateTime.convertHourlyTimestamp(),
64 | style = MaterialTheme.typography.labelMedium, maxLines = 1
65 | )
66 |
67 |
68 | }
69 | }
70 | }
71 |
72 | @Preview
73 | @Composable
74 | fun HourlyForecastsPreview() {
75 | AppTheme(isNetworkAvailable = true) {
76 | val item = HourlyForecastData(
77 | dateTime = "2023-12-04T12:00:00",
78 | iconPhrase = "Sunny",
79 | weatherIcon = 1,
80 | temperature = HourlyTemperature(value = 78, unit = "Celsius"),
81 | link = "https://example.com/forecast/12:00"
82 | )
83 |
84 | HourlyForecastItem(item) {}
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/home_screen/HomeScreenEvent.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.home_screen
2 |
3 | sealed class HomeScreenEvent {
4 | data class GetCurrentConditions(val locationId: String) : HomeScreenEvent()
5 | data class GetHourlyForecasts(val locationId: String) : HomeScreenEvent()
6 | data class GetDailyForecasts(val locationId: String) : HomeScreenEvent()
7 | }
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/home_screen/HomeScreenState.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.home_screen
2 |
3 | import com.weather.app.data.data_source.remote.response.DailyForecastData
4 | import com.weather.app.data.data_source.remote.response.HourlyForecastData
5 | import com.weather.app.data.data_source.remote.response.WeatherData
6 |
7 | sealed class HomeScreenState {
8 | data object Loading : HomeScreenState()
9 | sealed class Success : HomeScreenState() {
10 | data class Weather(val data: List) : Success()
11 | data class Hourly(val hourlyForecasts: List) : Success()
12 | data class Daily(val dailyForecasts: List) : Success()
13 | }
14 |
15 | data class Error(val error: String) : HomeScreenState()
16 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/home_screen/HomeScreenViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.home_screen
2 |
3 | import androidx.compose.runtime.mutableStateOf
4 | import androidx.lifecycle.ViewModel
5 | import androidx.lifecycle.viewModelScope
6 | import com.weather.app.data.data_source.local.WeatherDataStore
7 | import com.weather.app.domain.use_case.AppUseCases
8 | import com.weather.app.util.ConnectivityManager
9 | import dagger.hilt.android.lifecycle.HiltViewModel
10 | import kotlinx.coroutines.Dispatchers
11 | import kotlinx.coroutines.flow.MutableSharedFlow
12 | import kotlinx.coroutines.flow.MutableStateFlow
13 | import kotlinx.coroutines.flow.SharingStarted
14 | import kotlinx.coroutines.flow.StateFlow
15 | import kotlinx.coroutines.flow.asSharedFlow
16 | import kotlinx.coroutines.flow.launchIn
17 | import kotlinx.coroutines.flow.onEach
18 | import kotlinx.coroutines.flow.stateIn
19 | import kotlinx.coroutines.launch
20 | import kotlinx.coroutines.withContext
21 | import javax.inject.Inject
22 |
23 | @HiltViewModel
24 | class HomeScreenViewModel @Inject constructor(
25 | private val appUseCases: AppUseCases,
26 | private val connectivityManager: ConnectivityManager,
27 | private val dataStore: WeatherDataStore
28 | ) : ViewModel() {
29 |
30 | private val _eventFlow = MutableSharedFlow()
31 | val eventFlow = _eventFlow.asSharedFlow()
32 |
33 |
34 | var isDarkTheme = mutableStateOf(false)
35 |
36 | private val _state = MutableStateFlow(HomeScreenState.Loading)
37 | val state: StateFlow = _state.stateIn(
38 | scope = viewModelScope,
39 | started = SharingStarted.WhileSubscribed(),
40 | initialValue = HomeScreenState.Loading,
41 | )
42 | var currentCityKey = mutableStateOf("")
43 | private set
44 |
45 | init {
46 | viewModelScope.launch {
47 | dataStore.getDarkThemePrefs().collect {
48 | isDarkTheme.value = it
49 | }
50 | }
51 | getAll()
52 |
53 | }
54 |
55 | fun getAll() {
56 | viewModelScope.launch {
57 | dataStore.getCityPrefs().collect {
58 | currentCityKey.value = it
59 | val id = it.split("-")[1]
60 | onEvent(HomeScreenEvent.GetCurrentConditions(id))
61 | onEvent(HomeScreenEvent.GetHourlyForecasts(id))
62 | onEvent(HomeScreenEvent.GetDailyForecasts(id))
63 | }
64 |
65 | }
66 | }
67 |
68 | fun onEvent(event: HomeScreenEvent) {
69 | when (event) {
70 | is HomeScreenEvent.GetCurrentConditions -> {
71 | viewModelScope.launch { getCurrentConditions(event.locationId) }
72 | }
73 |
74 | is HomeScreenEvent.GetDailyForecasts -> {
75 | viewModelScope.launch { getDailyForecasts(event.locationId) }
76 | }
77 |
78 | is HomeScreenEvent.GetHourlyForecasts -> {
79 | viewModelScope.launch { getHourlyForecasts(event.locationId) }
80 | }
81 | }
82 | }
83 |
84 | private suspend fun getCurrentConditions(locationId: String) {
85 | if (!connectivityManager.isNetworkAvailable.value) {
86 | _eventFlow.emit(
87 | UiEvent.ShowSnackbar(
88 | message = "No network available"
89 | )
90 | )
91 | return
92 | }
93 | appUseCases.getCurrentConditions.invoke(locationId)
94 | .onEach { data ->
95 | _state.value = HomeScreenState.Loading
96 | if (data.data != null) {
97 | withContext(Dispatchers.Main) {
98 | _state.value = HomeScreenState.Success.Weather(data.data)
99 | }
100 | }
101 | if (data.error != null) {
102 | _state.value = HomeScreenState.Error(data.error)
103 | _eventFlow.emit(
104 | UiEvent.ShowSnackbar(
105 | message = data.error
106 | )
107 | )
108 | }
109 | }.launchIn(viewModelScope)
110 |
111 | }
112 |
113 | private suspend fun getHourlyForecasts(locationId: String) {
114 | if (!connectivityManager.isNetworkAvailable.value) {
115 | _eventFlow.emit(
116 | UiEvent.ShowSnackbar(
117 | message = "No network available"
118 | )
119 | )
120 | return
121 | }
122 | appUseCases.hourlyForecasts.invoke(locationId)
123 | .onEach { data ->
124 | _state.value = HomeScreenState.Loading
125 | if (data.data != null) {
126 |
127 | withContext(Dispatchers.Main) {
128 | _state.value = HomeScreenState.Success.Hourly(data.data)
129 | }
130 | }
131 | if (data.error != null) {
132 | _state.value = HomeScreenState.Error(data.error)
133 | _eventFlow.emit(
134 | UiEvent.ShowSnackbar(
135 | message = data.error
136 | )
137 | )
138 | }
139 | }.launchIn(viewModelScope)
140 |
141 | }
142 |
143 | private suspend fun getDailyForecasts(locationId: String) {
144 | if (!connectivityManager.isNetworkAvailable.value) {
145 | _eventFlow.emit(
146 | UiEvent.ShowSnackbar(
147 | message = "No network available"
148 | )
149 | )
150 | return
151 | }
152 | appUseCases.dailyForecasts.invoke(locationId)
153 | .onEach { data ->
154 | _state.value = HomeScreenState.Loading
155 | if (data.data != null) {
156 | withContext(Dispatchers.Main) {
157 | _state.value = HomeScreenState.Success.Daily(data.data)
158 | }
159 | }
160 | if (data.error != null) {
161 | _state.value = HomeScreenState.Error(data.error)
162 | _eventFlow.emit(
163 | UiEvent.ShowSnackbar(
164 | message = data.error
165 | )
166 | )
167 | }
168 | }.launchIn(viewModelScope)
169 |
170 | }
171 |
172 | fun switchTheme(newState: Boolean) {
173 | viewModelScope.launch { dataStore.setDarkThemePrefs(newState) }
174 |
175 | }
176 |
177 | sealed class UiEvent {
178 | data class ShowSnackbar(val message: String) : UiEvent()
179 | }
180 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/home_screen/navigation/HomeScreenDestination.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.home_screen.navigation
2 |
3 | import androidx.compose.animation.ExperimentalAnimationApi
4 | import androidx.navigation.NavController
5 | import androidx.navigation.NavGraphBuilder
6 | import androidx.navigation.compose.composable
7 | import com.weather.app.navigation.AppNavigationDestination
8 | import com.weather.app.presentation.home_screen.HomeScreen
9 |
10 | object HomeScreenDestination : AppNavigationDestination {
11 | override val route = "home_screen_route"
12 | override val destination = "home_screen_destination"
13 | }
14 |
15 | @OptIn(ExperimentalAnimationApi::class)
16 | fun NavGraphBuilder.homeScreen(navController: NavController) {
17 | composable(route = HomeScreenDestination.route) {
18 | HomeScreen(
19 | navController = navController
20 | )
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/navigation/MyApp.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.navigation
2 |
3 | import android.os.Bundle
4 | import androidx.compose.foundation.layout.Row
5 | import androidx.compose.foundation.layout.WindowInsets
6 | import androidx.compose.foundation.layout.WindowInsetsSides
7 | import androidx.compose.foundation.layout.consumeWindowInsets
8 | import androidx.compose.foundation.layout.fillMaxSize
9 | import androidx.compose.foundation.layout.only
10 | import androidx.compose.foundation.layout.padding
11 | import androidx.compose.foundation.layout.safeDrawing
12 | import androidx.compose.foundation.layout.windowInsetsPadding
13 | import androidx.compose.material3.Icon
14 | import androidx.compose.material3.MaterialTheme
15 | import androidx.compose.material3.NavigationBar
16 | import androidx.compose.material3.NavigationBarItem
17 | import androidx.compose.material3.Scaffold
18 | import androidx.compose.material3.Surface
19 | import androidx.compose.material3.Text
20 | import androidx.compose.runtime.Composable
21 | import androidx.compose.runtime.getValue
22 | import androidx.compose.runtime.remember
23 | import androidx.compose.ui.Modifier
24 | import androidx.compose.ui.graphics.Color
25 | import androidx.compose.ui.res.stringResource
26 | import androidx.compose.ui.unit.dp
27 | import androidx.compose.ui.zIndex
28 | import androidx.navigation.NavDestination
29 | import androidx.navigation.NavDestination.Companion.hierarchy
30 | import androidx.navigation.compose.NavHost
31 | import androidx.navigation.compose.currentBackStackEntryAsState
32 | import androidx.navigation.compose.rememberNavController
33 | import com.weather.app.navigation.AppTopLevelNavigation
34 | import com.weather.app.navigation.TOP_LEVEL_DESTINATIONS
35 | import com.weather.app.navigation.TopLevelDestination
36 | import com.weather.app.presentation.home_screen.navigation.HomeScreenDestination
37 | import com.weather.app.presentation.home_screen.navigation.homeScreen
38 | import com.weather.app.presentation.search_screen.navigation.SearchScreenDestination
39 | import com.weather.app.presentation.search_screen.navigation.searchScreen
40 | import com.weather.app.presentation.settings_screen.navigation.settingsScreen
41 | import com.weather.app.presentation.weather_animation_screen.navigation.animationScreen
42 | import com.weather.app.theme.AppTheme
43 |
44 | @Composable
45 | fun MyApp(isNetworkAvailable: Boolean, isDarkTheme: Boolean) {
46 | AppTheme(
47 | isNetworkAvailable = isNetworkAvailable,
48 | darkTheme = isDarkTheme,
49 | ) {
50 | val navController = rememberNavController()
51 | val appTopLevelNavigation = remember(navController) {
52 | AppTopLevelNavigation(navController)
53 | }
54 | val navBackStackEntry by navController.currentBackStackEntryAsState()
55 | val currentDestination = navBackStackEntry?.destination
56 |
57 | Scaffold(
58 | containerColor = Color.Transparent,
59 | contentColor = MaterialTheme.colorScheme.onBackground,
60 | bottomBar = {
61 | AppBottomBar(
62 | onNavigateToTopLevelDestination = appTopLevelNavigation::navigateTo,
63 | currentDestination = currentDestination
64 | )
65 | }
66 | ) { padding ->
67 | Row(
68 | Modifier
69 | .fillMaxSize()
70 | .windowInsetsPadding(
71 | WindowInsets.safeDrawing.only(
72 | WindowInsetsSides.Horizontal
73 | )
74 | )
75 | ) {
76 |
77 | NavHost(
78 | navController = navController,
79 | startDestination = HomeScreenDestination.route,
80 | modifier = Modifier
81 | .padding(padding)
82 | .consumeWindowInsets(padding)
83 | .zIndex(1f)
84 | ) {
85 | homeScreen(navController = navController)
86 | searchScreen(navController = navController)
87 | settingsScreen()
88 | animationScreen()
89 | }
90 | }
91 | }
92 | }
93 |
94 | }
95 |
96 | @Composable
97 | private fun AppBottomBar(
98 | onNavigateToTopLevelDestination: (TopLevelDestination) -> Unit,
99 | currentDestination: NavDestination?
100 | ) {
101 | // Wrap the navigation bar in a surface so the color behind the system
102 | // navigation is equal to the container color of the navigation bar.
103 | Surface(color = MaterialTheme.colorScheme.surface) {
104 | NavigationBar(
105 | modifier = Modifier.windowInsetsPadding(
106 | WindowInsets.safeDrawing.only(
107 | WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom
108 | )
109 | ),
110 | tonalElevation = 0.dp
111 | ) {
112 |
113 | TOP_LEVEL_DESTINATIONS.forEach { destination ->
114 | val selected =
115 | currentDestination?.hierarchy?.any { it.route == destination.route } == true
116 | NavigationBarItem(
117 | selected = selected,
118 | onClick =
119 | {
120 |
121 | onNavigateToTopLevelDestination(destination)
122 | },
123 | icon = {
124 | Icon(
125 | if (selected) {
126 | destination.selectedIcon
127 | } else {
128 | destination.unselectedIcon
129 | },
130 | contentDescription = null
131 | )
132 | },
133 | label = { Text(stringResource(destination.iconTextId)) }
134 | )
135 | }
136 | }
137 | }
138 | }
139 |
140 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/search_screen/SearchScreen.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.search_screen
2 |
3 | import androidx.compose.foundation.clickable
4 | import androidx.compose.foundation.layout.Arrangement
5 | import androidx.compose.foundation.layout.Box
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.foundation.layout.ExperimentalLayoutApi
8 | import androidx.compose.foundation.layout.FlowRow
9 | import androidx.compose.foundation.layout.Spacer
10 | import androidx.compose.foundation.layout.fillMaxSize
11 | import androidx.compose.foundation.layout.fillMaxWidth
12 | import androidx.compose.foundation.layout.height
13 | import androidx.compose.foundation.layout.padding
14 | import androidx.compose.foundation.lazy.LazyColumn
15 | import androidx.compose.foundation.lazy.items
16 | import androidx.compose.foundation.shape.RoundedCornerShape
17 | import androidx.compose.material.icons.Icons
18 | import androidx.compose.material.icons.filled.ArrowBack
19 | import androidx.compose.material.icons.filled.Clear
20 | import androidx.compose.material.icons.filled.Search
21 | import androidx.compose.material3.ExperimentalMaterial3Api
22 | import androidx.compose.material3.FilterChip
23 | import androidx.compose.material3.Icon
24 | import androidx.compose.material3.MaterialTheme
25 | import androidx.compose.material3.OutlinedTextField
26 | import androidx.compose.material3.Scaffold
27 | import androidx.compose.material3.SnackbarHost
28 | import androidx.compose.material3.SnackbarHostState
29 | import androidx.compose.material3.Text
30 | import androidx.compose.runtime.Composable
31 | import androidx.compose.runtime.LaunchedEffect
32 | import androidx.compose.runtime.getValue
33 | import androidx.compose.runtime.mutableStateOf
34 | import androidx.compose.runtime.remember
35 | import androidx.compose.runtime.setValue
36 | import androidx.compose.runtime.snapshotFlow
37 | import androidx.compose.ui.Modifier
38 | import androidx.compose.ui.platform.testTag
39 | import androidx.compose.ui.tooling.preview.Preview
40 | import androidx.compose.ui.unit.dp
41 | import androidx.hilt.navigation.compose.hiltViewModel
42 | import androidx.navigation.NavController
43 | import com.weather.app.domain.model.City
44 | import com.weather.app.presentation.components.CityItem
45 | import com.weather.app.testtags.TestTags
46 | import kotlinx.coroutines.Dispatchers
47 | import kotlinx.coroutines.ExperimentalCoroutinesApi
48 | import kotlinx.coroutines.FlowPreview
49 | import kotlinx.coroutines.flow.collect
50 | import kotlinx.coroutines.flow.collectLatest
51 | import kotlinx.coroutines.flow.debounce
52 | import kotlinx.coroutines.flow.distinctUntilChanged
53 | import kotlinx.coroutines.flow.filter
54 | import kotlinx.coroutines.flow.flowOn
55 | import kotlinx.coroutines.flow.map
56 |
57 | @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
58 | @Composable
59 | fun SearchScreen(
60 | navController: NavController,
61 | viewModel: SearchScreenViewModel = hiltViewModel(),
62 | q: String?
63 | ) {
64 |
65 | val state = viewModel.state.value
66 | val snackbarHostState = remember { SnackbarHostState() }
67 | var query by remember { mutableStateOf(q ?: "") }
68 |
69 | LaunchedEffect(key1 = true) {
70 | viewModel.eventFlow.collectLatest { event ->
71 | when (event) {
72 | is SearchScreenViewModel.UiEvent.ShowSnackbar -> {
73 | snackbarHostState.showSnackbar(
74 | message = event.message
75 | )
76 | }
77 | }
78 | }
79 | }
80 |
81 | LaunchedEffect(key1 = query) {
82 | snapshotFlow { query }
83 | .debounce(300)
84 | .filter { it.length >= 3 }
85 | .distinctUntilChanged()
86 | .map {
87 | viewModel.onEvent(SearchScreenEvent.CitiesSearchResults(it))
88 | }
89 | .flowOn(Dispatchers.Default)
90 | .collect()
91 | }
92 |
93 | Scaffold(
94 | topBar = {
95 | Icon(Icons.Default.ArrowBack, "", modifier = Modifier
96 | .padding(10.dp)
97 | .clickable {
98 | navController.popBackStack()
99 | }
100 | .testTag(TestTags.IconBack)
101 | )
102 | },
103 | snackbarHost = {
104 | SnackbarHost(
105 | snackbarHostState,
106 | modifier = Modifier.testTag(TestTags.SnackBar)
107 | )
108 | }
109 | ) {
110 | Box(modifier = Modifier.padding(it)) {
111 | Column(
112 | modifier = Modifier
113 | .fillMaxSize()
114 | .padding(16.dp)
115 | ) {
116 |
117 | OutlinedTextField(
118 | shape = RoundedCornerShape(200.dp),
119 | leadingIcon = {
120 | Icon(
121 | Icons.Default.Search,
122 | contentDescription = ""
123 | )
124 | },
125 | value = query,
126 | onValueChange = { value ->
127 | query = value
128 | },
129 | placeholder = { Text("Search for cities") },
130 | modifier = Modifier
131 | .fillMaxWidth()
132 | .padding(bottom = 16.dp)
133 | .testTag(TestTags.SearchField),
134 | trailingIcon = {
135 | if (query.isNotEmpty()) {
136 | Icon(
137 | imageVector = Icons.Default.Clear,
138 | contentDescription = null,
139 | modifier = Modifier
140 | .clickable {
141 | query = ""
142 | }
143 | .testTag(TestTags.ClearIcon)
144 | )
145 | }
146 | }
147 | )
148 |
149 | Spacer(modifier = Modifier.height(16.dp))
150 |
151 | if (state.data.isNotEmpty() && query.isNotEmpty()) {
152 | LazyColumn {
153 | items(state.data) { cityData ->
154 | CityItem(city = cityData) { city ->
155 | viewModel.onEvent(SearchScreenEvent.CitySelection(city))
156 | query = ""
157 | }
158 | }
159 | }
160 | }
161 | if (query.isEmpty()) {
162 | RecentChips(state, viewModel)
163 | }
164 | }
165 | }
166 |
167 | }
168 | }
169 |
170 | @Composable
171 | @OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class)
172 | private fun RecentChips(
173 | state: SearchScreenState,
174 | viewModel: SearchScreenViewModel
175 | ) {
176 | if (state.selectedCities.isNotEmpty())
177 | Text(
178 | "Recent locations:",
179 | style = MaterialTheme.typography.titleMedium,
180 | color = MaterialTheme.colorScheme.onBackground,
181 | modifier = Modifier
182 | .fillMaxWidth()
183 | .padding(16.dp)
184 | .testTag(TestTags.RecentLocationsText)
185 | )
186 | FlowRow(
187 | modifier = Modifier.padding(2.dp),
188 | horizontalArrangement = Arrangement.spacedBy(2.dp),
189 | ) {
190 | state.selectedCities.forEach { city ->
191 | FilterChip(modifier = Modifier.padding(end = 5.dp),
192 | trailingIcon = {
193 | Icon(
194 | Icons.Default.Clear,
195 | contentDescription = "", modifier = Modifier.clickable {
196 | viewModel.onEvent(SearchScreenEvent.DeleteCity(city))
197 | }
198 | )
199 | },
200 | shape = RoundedCornerShape(200.dp),
201 | selected = city.id == viewModel.currentLocationId.value,
202 | onClick = {
203 | viewModel.onEvent(SearchScreenEvent.CitySelection(city))
204 | },
205 | label = {
206 | Text(text = city.localizedName)
207 | })
208 | }
209 | }
210 | }
211 |
212 | @Preview
213 | @Composable
214 | fun RecentChipsPreview() {
215 | val recentCities = listOf(
216 | City("1", "Cairo", "Egypt", "Cairo"),
217 | City("2", "Alex", "Egypt", "Alex")
218 | )
219 | val viewModel: SearchScreenViewModel = hiltViewModel()
220 | RecentChips(state = SearchScreenState(selectedCities = recentCities), viewModel)
221 | }
222 |
223 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/search_screen/SearchScreenEvent.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.search_screen
2 |
3 | import com.weather.app.domain.model.City
4 |
5 | sealed class SearchScreenEvent {
6 | data class CitiesSearchResults(val query: String) : SearchScreenEvent()
7 | data class CitySelection(val city: City) : SearchScreenEvent()
8 | data class DeleteCity(val city: City) : SearchScreenEvent()
9 | data object DisplaySelectedCities : SearchScreenEvent()
10 |
11 | }
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/search_screen/SearchScreenState.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.search_screen
2 |
3 | import com.weather.app.domain.model.City
4 |
5 | data class SearchScreenState(
6 | val data: List = emptyList(),
7 | val selectedCities: List = emptyList()
8 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/search_screen/SearchScreenViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.search_screen
2 |
3 | import androidx.compose.runtime.State
4 | import androidx.compose.runtime.mutableStateOf
5 | import androidx.lifecycle.SavedStateHandle
6 | import androidx.lifecycle.ViewModel
7 | import androidx.lifecycle.viewModelScope
8 | import com.weather.app.data.data_source.local.WeatherDataStore
9 | import com.weather.app.data.data_source.local.fromEntityList
10 | import com.weather.app.domain.use_case.AppUseCases
11 | import com.weather.app.util.ConnectivityManager
12 | import dagger.hilt.android.lifecycle.HiltViewModel
13 | import kotlinx.coroutines.Dispatchers
14 | import kotlinx.coroutines.flow.MutableSharedFlow
15 | import kotlinx.coroutines.flow.asSharedFlow
16 | import kotlinx.coroutines.flow.launchIn
17 | import kotlinx.coroutines.flow.onEach
18 | import kotlinx.coroutines.launch
19 | import kotlinx.coroutines.withContext
20 | import javax.inject.Inject
21 |
22 | @HiltViewModel
23 | class SearchScreenViewModel @Inject constructor(
24 | private val appUseCases: AppUseCases,
25 | private val connectivityManager: ConnectivityManager,
26 | private val dataStore: WeatherDataStore,
27 | savedStateHandle: SavedStateHandle
28 | ) : ViewModel() {
29 |
30 |
31 | val query = savedStateHandle.get("q")
32 | private val _eventFlow = MutableSharedFlow()
33 | val eventFlow = _eventFlow.asSharedFlow()
34 |
35 | private val _state = mutableStateOf(SearchScreenState())
36 | val state: State = _state
37 |
38 |
39 | var loading = mutableStateOf(false)
40 | private set
41 |
42 | var currentLocationId = mutableStateOf("")
43 | private set
44 |
45 | var isConnected = mutableStateOf(false)
46 | private set
47 |
48 | init {
49 | viewModelScope.launch {
50 | dataStore.getCityPrefs().collect {
51 | currentLocationId.value = it.split("-")[1]
52 | onEvent(SearchScreenEvent.DisplaySelectedCities)
53 | }
54 | }
55 |
56 | }
57 |
58 | fun onEvent(event: SearchScreenEvent) {
59 | when (event) {
60 | is SearchScreenEvent.CitiesSearchResults -> {
61 | viewModelScope.launch {
62 | doSearch(event)
63 | }
64 | }
65 |
66 | is SearchScreenEvent.CitySelection -> {
67 | viewModelScope.launch {
68 | withContext(Dispatchers.IO) {
69 | appUseCases.addCityOffline(event.city)
70 | }
71 | dataStore.setCityPrefs("${event.city.localizedName}, ${event.city.country}-${event.city.id}")
72 | }
73 | }
74 |
75 | SearchScreenEvent.DisplaySelectedCities -> {
76 | viewModelScope.launch(Dispatchers.IO) {
77 | appUseCases.getCities.invoke().collect {
78 | withContext(Dispatchers.Main) {
79 | _state.value = state.value.copy(
80 | selectedCities = it.fromEntityList()
81 | )
82 | }
83 | }
84 | }
85 |
86 | }
87 |
88 | is SearchScreenEvent.DeleteCity -> {
89 | viewModelScope.launch {
90 | appUseCases.deleteCity(event.city)
91 | }
92 | }
93 | }
94 | }
95 |
96 | private suspend fun doSearch(event: SearchScreenEvent.CitiesSearchResults) {
97 | if (!connectivityManager.isNetworkAvailable.value) {
98 | _eventFlow.emit(
99 | UiEvent.ShowSnackbar(
100 | message = "No network available"
101 | )
102 | )
103 | return
104 | }
105 | appUseCases.getSearchResults.invoke(event.query)
106 | .onEach { data ->
107 | loading.value = data.loading
108 | if (data.data != null) {
109 | withContext(Dispatchers.Main) {
110 | _state.value = state.value.copy(
111 | data = data.data
112 | )
113 | }
114 |
115 | }
116 | if (data.error != null) {
117 | _eventFlow.emit(
118 | UiEvent.ShowSnackbar(
119 | message = data.error
120 |
121 | )
122 | )
123 | }
124 | }.launchIn(viewModelScope)
125 | }
126 |
127 | sealed class UiEvent {
128 | data class ShowSnackbar(val message: String) : UiEvent()
129 | }
130 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/search_screen/navigation/SearchScreenDestination.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.search_screen.navigation
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import androidx.navigation.NavController
6 | import androidx.navigation.NavGraphBuilder
7 | import androidx.navigation.NavType
8 | import androidx.navigation.compose.composable
9 | import androidx.navigation.navArgument
10 | import androidx.navigation.navDeepLink
11 | import com.weather.app.navigation.AppNavigationDestination
12 | import com.weather.app.presentation.search_screen.SearchScreen
13 |
14 | object SearchScreenDestination : AppNavigationDestination {
15 | override val route = "search_screen_route"
16 | override val destination = "search_screen_destination"
17 | }
18 |
19 | fun NavGraphBuilder.searchScreen(navController: NavController) {
20 | composable(
21 | route = SearchScreenDestination.route + "/{q}",
22 | arguments = listOf(
23 | navArgument("q") {
24 | type = NavType.StringType
25 | defaultValue = "default"
26 | }
27 | ),
28 | deepLinks = listOf(navDeepLink {
29 | uriPattern = "https://weatherapp.com/{q}"
30 | action = Intent.ACTION_VIEW
31 | })
32 | ) {
33 | val bundle = navController.previousBackStackEntry?.savedStateHandle?.get(
34 | "bundleKey"
35 | )
36 | val qureyFromBundle = bundle?.getString("q")
37 | val qureyFromArguments = it.arguments?.getString("q")
38 |
39 | SearchScreen(
40 | navController = navController,
41 | q = qureyFromBundle
42 | )
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/settings_screen/SettingsScreen.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.settings_screen
2 |
3 | import androidx.compose.foundation.Image
4 | import androidx.compose.foundation.layout.Arrangement
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.Spacer
7 | import androidx.compose.foundation.layout.fillMaxSize
8 | import androidx.compose.foundation.layout.height
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.material3.MaterialTheme
11 | import androidx.compose.material3.Text
12 | import androidx.compose.runtime.Composable
13 | import androidx.compose.ui.Alignment
14 | import androidx.compose.ui.Modifier
15 | import androidx.compose.ui.res.painterResource
16 | import androidx.compose.ui.res.stringResource
17 | import androidx.compose.ui.unit.dp
18 | import com.weather.app.BuildConfig
19 | import com.weather.app.R
20 |
21 | @Composable
22 | fun SettingsScreen() {
23 | Column(
24 | modifier = Modifier
25 | .fillMaxSize()
26 | .padding(32.dp),
27 | horizontalAlignment = Alignment.CenterHorizontally,
28 | verticalArrangement = Arrangement.Center
29 | ) {
30 |
31 | Image(
32 | painterResource(R.drawable.app_icon),
33 | contentDescription = ""
34 | )
35 |
36 |
37 | Spacer(modifier = Modifier.height(60.dp))
38 |
39 | Text(
40 | text = stringResource(R.string.app_name),
41 | color = MaterialTheme.colorScheme.onBackground
42 | )
43 |
44 | Text(
45 | text = "v${BuildConfig.VERSION_NAME} #${BuildConfig.VERSION_CODE}",
46 | color = MaterialTheme.colorScheme.onBackground
47 | )
48 |
49 | }
50 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/settings_screen/navigation/SettingsScreenDestination.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.settings_screen.navigation
2 |
3 | import androidx.navigation.NavGraphBuilder
4 | import androidx.navigation.compose.composable
5 | import com.weather.app.navigation.AppNavigationDestination
6 | import com.weather.app.presentation.settings_screen.SettingsScreen
7 |
8 | object SettingsScreenDestination : AppNavigationDestination {
9 | override val route = "settings_screen_route"
10 | override val destination = "settings_screen_destination"
11 | }
12 |
13 |
14 | fun NavGraphBuilder.settingsScreen() {
15 | composable(route = SettingsScreenDestination.route) {
16 | SettingsScreen()
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/presentation/weather_animation_screen/navigation/WeatherAnimationScreenDestination.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.presentation.weather_animation_screen.navigation
2 |
3 | import androidx.navigation.NavGraphBuilder
4 | import androidx.navigation.compose.composable
5 | import com.weather.app.navigation.AppNavigationDestination
6 | import com.weather.app.presentation.weather_animation_screen.AnimationScreen
7 |
8 | object AnimationScreenDestination : AppNavigationDestination {
9 | override val route = "animation_screen_route"
10 | override val destination = "animation_screen_destination"
11 | }
12 |
13 |
14 | fun NavGraphBuilder.animationScreen() {
15 | composable(route = AnimationScreenDestination.route) {
16 | AnimationScreen()
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/testtags/TestTags.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.testtags
2 |
3 | object TestTags {
4 | const val ClearIcon = "ClearIcon"
5 | const val RecentLocationsText = "RecentLocationsText"
6 | const val SearchField = "SearchField"
7 | const val Reload = "Reload"
8 | const val SnackBar = "SnackBar"
9 | const val NoDataFound = "NoDataFound"
10 | const val IconBack = "IconBack"
11 | const val IconSearch = "IconSearch"
12 | const val DarkModeImageTag = "DarkModeImage"
13 | const val LightModeImageTag = "LightModeImage"
14 | const val CustomSwitch = "CustomSwitch"
15 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val AppColor = Color(0xFFF5C519)
6 |
7 |
8 | val Blue400 = Color(0xFF42A5F5)
9 |
10 | val Teal300 = Color(0xFF1AC6FF)
11 |
12 | val Grey1 = Color(0xFFF2F2F2)
13 |
14 | val Black1 = Color(0xA9222222)
15 | val Black2 = Color(0xFF000000)
16 |
17 | val RedErrorDark = Color(0xFFB00020)
18 | val RedErrorLight = Color(0xFFEF5350)
19 |
20 | val SurfaceDark = Color(0xFF252323)
21 | val SurfaceLight = Color(0xC4FFFFFF)
22 |
23 |
24 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/theme/Shape.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.theme
2 |
3 | import androidx.compose.foundation.shape.RoundedCornerShape
4 | import androidx.compose.material3.Shapes
5 | import androidx.compose.ui.unit.dp
6 |
7 | val Shapes = Shapes(
8 | small = RoundedCornerShape(4.dp),
9 | medium = RoundedCornerShape(4.dp),
10 | large = RoundedCornerShape(0.dp)
11 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.theme
2 |
3 | import android.os.Build
4 | import androidx.compose.foundation.isSystemInDarkTheme
5 | import androidx.compose.foundation.layout.Box
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.foundation.layout.fillMaxSize
8 | import androidx.compose.material3.MaterialTheme
9 | import androidx.compose.material3.darkColorScheme
10 | import androidx.compose.material3.dynamicDarkColorScheme
11 | import androidx.compose.material3.dynamicLightColorScheme
12 | import androidx.compose.material3.lightColorScheme
13 | import androidx.compose.runtime.Composable
14 | import androidx.compose.ui.Modifier
15 | import androidx.compose.ui.graphics.Color
16 | import androidx.compose.ui.platform.LocalContext
17 | import com.weather.app.presentation.components.GenericDialog
18 | import com.weather.app.presentation.components.GenericDialogInfo
19 | import com.weather.app.presentation.components.NoConnectionAvailable
20 | import java.util.Queue
21 |
22 | private val lightThemeColors = lightColorScheme(
23 | primary = AppColor,
24 | primaryContainer = Blue400,
25 | onPrimary = Black2,
26 | secondary = Color.White,
27 | secondaryContainer = Teal300,
28 | error = RedErrorDark,
29 | onError = RedErrorLight,
30 | background = Grey1,
31 | onBackground = Color.Black,
32 | surface = SurfaceLight
33 | )
34 |
35 | private val darkThemeColors = darkColorScheme(
36 | primary = AppColor,
37 | onPrimary = Color.White,
38 | secondary = Black1,
39 | onSecondary = Color.White,
40 | error = RedErrorLight,
41 | background = Color.Black,
42 | onBackground = Color.White,
43 | surface = SurfaceDark,
44 | onSurface = Color.White
45 | )
46 |
47 |
48 | @Composable
49 | fun AppTheme(
50 | darkTheme: Boolean = isSystemInDarkTheme(),
51 | dynamicColor: Boolean = false,
52 | isNetworkAvailable: Boolean,
53 | dialogQueue: Queue? = null,
54 | content: @Composable () -> Unit
55 | ) {
56 | val colorScheme = when {
57 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
58 | val context = LocalContext.current
59 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
60 | }
61 |
62 | darkTheme -> darkThemeColors
63 | else -> lightThemeColors
64 | }
65 | MaterialTheme(
66 | colorScheme = colorScheme,
67 | typography = Typography,
68 | shapes = Shapes
69 | ) {
70 | Box(
71 | modifier = Modifier
72 | .fillMaxSize()
73 | //.background(color = if (!darkTheme) Grey1 else Color.Black)
74 | ) {
75 | Column {
76 | if (!isNetworkAvailable) {
77 | NoConnectionAvailable()
78 | }
79 | content()
80 | }
81 |
82 | ProcessDialogQueue(dialogQueue = dialogQueue)
83 |
84 |
85 | }
86 | }
87 | }
88 |
89 | @Composable
90 | fun ProcessDialogQueue(
91 | dialogQueue: Queue?,
92 | ) {
93 | dialogQueue?.peek()?.let { dialogInfo ->
94 | GenericDialog(
95 | onDismiss = dialogInfo.onDismiss,
96 | title = dialogInfo.title,
97 | description = dialogInfo.description,
98 | positiveAction = dialogInfo.positiveAction,
99 | negativeAction = dialogInfo.negativeAction
100 | )
101 | }
102 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp
15 | )
16 | /* Other default text styles to override
17 | button = TextStyle(
18 | fontFamily = FontFamily.Default,
19 | fontWeight = FontWeight.W500,
20 | fontSize = 14.sp
21 | ),
22 | caption = TextStyle(
23 | fontFamily = FontFamily.Default,
24 | fontWeight = FontWeight.Normal,
25 | fontSize = 12.sp
26 | )
27 | */
28 | )
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/ConnectionFlowCallback.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 | import android.content.Context
4 | import android.content.Context.CONNECTIVITY_SERVICE
5 | import android.net.ConnectivityManager
6 | import android.net.Network
7 | import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET
8 | import android.net.NetworkRequest
9 | import kotlinx.coroutines.Dispatchers
10 | import kotlinx.coroutines.ExperimentalCoroutinesApi
11 | import kotlinx.coroutines.channels.awaitClose
12 | import kotlinx.coroutines.flow.callbackFlow
13 | import kotlinx.coroutines.launch
14 | import kotlinx.coroutines.withContext
15 |
16 | @ExperimentalCoroutinesApi
17 | class ConnectionFlowCallback(context: Context) {
18 |
19 | private val cm = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
20 | private val validNetworks: MutableSet = HashSet()
21 |
22 |
23 | @ExperimentalCoroutinesApi
24 | fun startNetworkCallback() = callbackFlow {
25 | val networkCallback = object : ConnectivityManager.NetworkCallback() {
26 |
27 | override fun onAvailable(network: Network) {
28 | launch(Dispatchers.IO) {
29 | val hasInternet = DoesNetworkHaveInternet.execute(network.socketFactory)
30 | if (hasInternet) {
31 | withContext(Dispatchers.Main) {
32 | validNetworks.add(network)
33 | send(true)
34 | }
35 | }
36 | }
37 | }
38 |
39 | override fun onLost(network: Network) {
40 | launch(Dispatchers.Main) {
41 | validNetworks.remove(network)
42 | send(false)
43 | }
44 | }
45 | }
46 |
47 | cm.registerNetworkCallback(
48 | NetworkRequest.Builder().addCapability(NET_CAPABILITY_INTERNET).build(),
49 | networkCallback
50 | )
51 |
52 | awaitClose { cm.unregisterNetworkCallback(networkCallback) }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/ConnectivityManager.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 | import android.app.Application
4 | import androidx.compose.runtime.mutableStateOf
5 | import androidx.lifecycle.LifecycleOwner
6 | import androidx.lifecycle.lifecycleScope
7 | import kotlinx.coroutines.ExperimentalCoroutinesApi
8 | import kotlinx.coroutines.launch
9 | import javax.inject.Inject
10 | import javax.inject.Singleton
11 |
12 | @OptIn(ExperimentalCoroutinesApi::class)
13 | @Singleton
14 | class ConnectivityManager @Inject constructor(application: Application) {
15 | private val connectionFlow = ConnectionFlowCallback(application)
16 |
17 | // observe this in ui
18 | val isNetworkAvailable = mutableStateOf(false)
19 |
20 |
21 | fun registerConnectionObserver(lifecycleOwner: LifecycleOwner) {
22 | lifecycleOwner.lifecycleScope.launch {
23 | connectionFlow.startNetworkCallback().collect { isConnected ->
24 | isNetworkAvailable.value = isConnected
25 | }
26 | }
27 | }
28 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/Constants.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 | const val TAG = "AppDebug"
4 | const val BASE_URL = "http://dataservice.accuweather.com/"
5 |
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/DialogQueue.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 | import androidx.compose.runtime.MutableState
4 | import androidx.compose.runtime.mutableStateOf
5 | import com.weather.app.presentation.components.GenericDialogInfo
6 | import com.weather.app.presentation.components.PositiveAction
7 | import java.util.ArrayDeque
8 | import java.util.LinkedList
9 | import java.util.Queue
10 |
11 | class DialogQueue {
12 | val queue: MutableState> = mutableStateOf(
13 | LinkedList()
14 | )
15 |
16 | fun removeHeadMessage() {
17 | if (queue.value.isNotEmpty()) {
18 | val update = queue.value
19 | update.remove() // remove first (oldest message)
20 | queue.value = ArrayDeque() // force recompose (bug?)
21 | queue.value = update
22 | }
23 | }
24 |
25 | fun appendErrorMessage(title: String, description: String) {
26 | queue.value.offer(
27 | GenericDialogInfo.Builder()
28 | .title(title)
29 | .onDismiss(this::removeHeadMessage)
30 | .description(description)
31 | .positive(
32 | PositiveAction(
33 | positiveBtnTxt = "Ok",
34 | onPositiveAction = this::removeHeadMessage,
35 | )
36 | )
37 | .build()
38 | )
39 | }
40 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/DoesNetworkHaveInternet.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 | import android.util.Log
4 | import java.io.IOException
5 | import java.net.InetSocketAddress
6 | import javax.net.SocketFactory
7 |
8 | object DoesNetworkHaveInternet {
9 |
10 | fun execute(socketFactory: SocketFactory): Boolean {
11 | return try {
12 | Log.d(TAG, "execute: PINGING GOOGLE")
13 | val socket = socketFactory.createSocket()
14 | socket.connect(
15 | InetSocketAddress("8.8.8.8", 53),
16 | 1500
17 | )
18 | socket.close()
19 | Log.d(TAG, "execute: PING SUCCESS")
20 | true
21 |
22 | } catch (e: IOException) {
23 | Log.e(TAG, "execute: No internet connection ${e}")
24 | false
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/Extensions.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/ImageUtils.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/SavedStateHandleExtensions.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 | import androidx.lifecycle.SavedStateHandle
4 | import androidx.lifecycle.ViewModel
5 | import kotlin.properties.ReadWriteProperty
6 | import kotlin.reflect.KProperty
7 |
8 | /**
9 | * Delegate for accessing [ViewModel] property through [SavedStateHandle]
10 | */
11 | fun SavedStateHandle.property(): ReadWriteProperty = SavedStateProperty(this)
12 |
13 | /**
14 | * Delegate for accessing [ViewModel] property through [SavedStateHandle] with a default initial value
15 | */
16 | fun SavedStateHandle.property(default: T): ReadWriteProperty =
17 | SavedStatePropertyWithDefault(this, default)
18 |
19 | private class SavedStateProperty(
20 | private val handle: SavedStateHandle
21 | ) : ReadWriteProperty {
22 |
23 | override fun getValue(thisRef: Any, property: KProperty<*>): T? {
24 | return handle[property.name]
25 | }
26 |
27 | override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) {
28 | handle[property.name] = value
29 | }
30 | }
31 |
32 | private class SavedStatePropertyWithDefault(
33 | private val handle: SavedStateHandle,
34 | private val default: T
35 | ) : ReadWriteProperty {
36 |
37 | override fun getValue(thisRef: Any, property: KProperty<*>): T {
38 | return handle[property.name] ?: default
39 | }
40 |
41 | override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
42 | handle[property.name] = value
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/SnackbarUtil.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 | import androidx.compose.foundation.layout.Box
4 | import androidx.compose.foundation.layout.fillMaxWidth
5 | import androidx.compose.material3.Snackbar
6 | import androidx.compose.material3.SnackbarHost
7 | import androidx.compose.material3.SnackbarHostState
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.runtime.LaunchedEffect
10 | import androidx.compose.runtime.mutableStateOf
11 | import androidx.compose.runtime.remember
12 | import androidx.compose.runtime.rememberCoroutineScope
13 | import androidx.compose.ui.Alignment
14 | import androidx.compose.ui.Modifier
15 | import androidx.compose.ui.zIndex
16 | import com.weather.app.theme.Grey1
17 | import kotlinx.coroutines.launch
18 |
19 | class SnackbarUtil {
20 |
21 | companion object {
22 | private val snackbarMessage = mutableStateOf("")
23 | private var isSnackbarVisible = mutableStateOf(false)
24 |
25 | fun showSnackbar(message: String) {
26 | snackbarMessage.value = message
27 | isSnackbarVisible.value = true
28 | }
29 |
30 | fun getSnackbarMessage() = snackbarMessage
31 |
32 | fun hideSnackbar() {
33 | isSnackbarVisible.value = false
34 | }
35 |
36 | fun isSnackbarVisible() = isSnackbarVisible
37 |
38 | @Composable
39 | fun SnackbarWithoutScaffold(
40 | message: String,
41 | isVisible: Boolean,
42 | onVisibilityChange: (Boolean) -> Unit
43 | ) {
44 | val snackState = remember { SnackbarHostState() }
45 | val snackScope = rememberCoroutineScope()
46 |
47 | Box(
48 | modifier = Modifier
49 | .fillMaxWidth()
50 | .zIndex(10f),
51 | contentAlignment = Alignment.BottomCenter
52 | ) {
53 | SnackbarHost(
54 | modifier = Modifier,
55 | hostState = snackState
56 | ) {
57 | Snackbar(
58 | snackbarData = it,
59 | containerColor = Grey1,
60 | contentColor = androidx.compose.ui.graphics.Color.White
61 | )
62 | }
63 | }
64 |
65 | if (isVisible) {
66 | LaunchedEffect(Unit) {
67 | snackScope.launch {
68 | snackState.showSnackbar(message)
69 | onVisibilityChange(false)
70 | }
71 | }
72 | }
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/app/src/main/java/com/weather/app/util/Utils.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.util
2 |
3 | import androidx.navigation.NavHostController
4 |
5 | fun NavHostController.navigateSingleTop(route: String) {
6 | this.navigate(route) {
7 | popUpTo(route)
8 | launchSingleTop = true
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/accuweather_splash_brand.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/accuweather_splash_brand.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/app_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/app_icon.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/clouds.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/clouds.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/cloudy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/cloudy.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/cloudy_night.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/cloudy_night.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/img.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/img.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/partly_cloudy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/partly_cloudy.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/rain_lightning.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/rain_lightning.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/rainy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/rainy.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/sunny.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/sunny.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/sunny_night.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/drawable/sunny_night.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/values-night/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Animation
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values-v31/splash_theme.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
12 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FF404040
4 | #FF000000
5 | #FFFFFFFF
6 | #FFFFFF
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFFFFF
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/splash_theme.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Weather App
3 | Home
4 | Settings
5 | Animation
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
11 |
12 |
16 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/network_security_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/MainDispatcherRule.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature
2 |
3 | import kotlinx.coroutines.Dispatchers
4 | import kotlinx.coroutines.ExperimentalCoroutinesApi
5 | import kotlinx.coroutines.test.TestDispatcher
6 | import kotlinx.coroutines.test.UnconfinedTestDispatcher
7 | import kotlinx.coroutines.test.resetMain
8 | import kotlinx.coroutines.test.setMain
9 | import org.junit.rules.TestWatcher
10 | import org.junit.runner.Description
11 |
12 | @OptIn(ExperimentalCoroutinesApi::class)
13 | class MainDispatcherRule(
14 | private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher()
15 | ) : TestWatcher() {
16 | override fun starting(description: Description) {
17 | Dispatchers.setMain(testDispatcher)
18 | }
19 |
20 | override fun finished(description: Description) {
21 | Dispatchers.resetMain()
22 | }
23 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/data/repository/FakeWeatherAppRepository.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.data.repository
2 |
3 | import com.weather.app.data.data_source.local.CityEntity
4 | import com.weather.app.data.data_source.local.toEntityList
5 | import com.weather.app.data.data_source.remote.RetrofitService
6 | import com.weather.app.data.data_source.remote.fromEntityList
7 | import com.weather.app.data.data_source.remote.response.DailyForecastData
8 | import com.weather.app.data.data_source.remote.response.HourlyForecastData
9 | import com.weather.app.data.data_source.remote.response.WeatherData
10 | import com.weather.app.domain.DataState
11 | import com.weather.app.domain.model.City
12 | import com.weather.app.domain.repository.AppRepository
13 | import kotlinx.coroutines.flow.Flow
14 | import kotlinx.coroutines.flow.flow
15 | import kotlinx.coroutines.flow.flowOf
16 |
17 | class FakeWeatherAppRepository(
18 | private val retrofitService: RetrofitService? = null,
19 | ) : AppRepository {
20 |
21 | private val citie = mutableListOf()
22 |
23 |
24 | override fun getSearchResults(query: String): Flow>> = flow {
25 | try {
26 | emit(DataState.loading())
27 | val response = retrofitService?.autoCompleteSearch(q = query)
28 | emit(DataState.success(response?.fromEntityList()!!))
29 | } catch (e: Exception) {
30 | emit(DataState.error(e.message ?: "Unknown error"))
31 | }
32 |
33 | }
34 |
35 | override suspend fun addCityOffline(city: City) {
36 | citie.add(city)
37 | }
38 |
39 | override suspend fun deleteCity(city: City) {
40 | citie.remove(city)
41 | }
42 |
43 | override suspend fun getCities(): Flow> {
44 | return flowOf(citie.toEntityList())
45 | }
46 |
47 | override suspend fun getCurrentConditions(locationId: String): Flow>> =
48 | flow {
49 | try {
50 | emit(DataState.loading())
51 | val response = retrofitService?.currentConditions("")
52 | emit(DataState.success(response ?: emptyList()))
53 | } catch (e: Exception) {
54 | emit(DataState.error(e.message ?: "Unknown error"))
55 | }
56 | }
57 |
58 | override suspend fun getHourlyForecasts(locationId: String): Flow>> =
59 | flow {
60 | try {
61 | emit(DataState.loading())
62 | val response = retrofitService?.getHourlyForecastByCityCode("")
63 | emit(DataState.success(response ?: emptyList()))
64 | } catch (e: Exception) {
65 | emit(DataState.error(e.message ?: "Unknown error"))
66 | }
67 | }
68 |
69 | override suspend fun getDailyForecasts(locationId: String): Flow>> =
70 | flow {
71 | try {
72 | emit(DataState.loading())
73 | val response = retrofitService?.getDailyForecastByCityCode("")
74 | emit(DataState.success(response?.dailyForecasts ?: emptyList()))
75 | } catch (e: Exception) {
76 | emit(DataState.error(e.message ?: "Unknown error"))
77 | }
78 | }
79 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/domain/use_case/AddCityOfflineTest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.domain.use_case
2 |
3 | import com.google.common.truth.Truth.assertThat
4 | import com.weather.app.app_feature.data.repository.FakeWeatherAppRepository
5 | import com.weather.app.data.data_source.local.mapFromDomainModel
6 | import com.weather.app.data.repository.AppRepositoryImpl
7 | import com.weather.app.domain.model.City
8 | import com.weather.app.domain.use_case.AddCityOffline
9 | import io.mockk.coEvery
10 | import io.mockk.coVerify
11 | import io.mockk.impl.annotations.MockK
12 | import io.mockk.junit4.MockKRule
13 | import io.mockk.just
14 | import io.mockk.runs
15 | import kotlinx.coroutines.flow.first
16 | import kotlinx.coroutines.flow.flowOf
17 | import kotlinx.coroutines.runBlocking
18 | import org.junit.Before
19 | import org.junit.Rule
20 | import org.junit.Test
21 |
22 | class AddCityOfflineTest {
23 | @get:Rule
24 | val mockkRule = MockKRule(this)
25 |
26 | private lateinit var addCityOffline: AddCityOffline
27 | private lateinit var addCityOfflineMockk: AddCityOffline
28 |
29 | private lateinit var fakeRepository: FakeWeatherAppRepository
30 |
31 | @MockK
32 | private lateinit var mockRepository: AppRepositoryImpl
33 |
34 | @Before
35 | fun setUp() {
36 | fakeRepository = FakeWeatherAppRepository()
37 | addCityOffline = AddCityOffline(fakeRepository)
38 |
39 | addCityOfflineMockk = AddCityOffline(mockRepository)
40 |
41 | }
42 |
43 | @Test
44 | fun addCityOffline_ReturnSuccess() = runBlocking {
45 | val city =
46 | City(id = "1", localizedName = "Cairo", country = "Egypt", administrativeArea = "CA")
47 | addCityOffline(city = city)
48 | val result = fakeRepository.getCities().first()
49 | assertThat(result.size).isEqualTo(1)
50 | assertThat(result[0].id).isEqualTo("1")
51 | assertThat(result[0].localizedName).isEqualTo("Cairo")
52 | }
53 |
54 | @Test
55 | fun mockkAddCityOffline_ReturnSuccess() = runBlocking {
56 |
57 | val city =
58 | City(id = "1", localizedName = "Cairo", country = "Egypt", administrativeArea = "CA")
59 |
60 | coEvery { mockRepository.addCityOffline(city) } just runs
61 | addCityOfflineMockk(city = city)
62 |
63 | coEvery { mockRepository.getCities() } returns flowOf(
64 | listOf(
65 | city.mapFromDomainModel()
66 | )
67 | )
68 |
69 | val result = mockRepository.getCities().first()
70 | coVerify {
71 | mockRepository.addCityOffline(city)
72 | mockRepository.getCities()
73 | }
74 | assertThat(result.size).isEqualTo(1)
75 | assertThat(result[0].id).isEqualTo("1")
76 | assertThat(result[0].localizedName).isEqualTo("Cairo")
77 | }
78 |
79 |
80 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/domain/use_case/DeleteCityTest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.domain.use_case
2 |
3 | import com.google.common.truth.Truth.assertThat
4 | import com.weather.app.app_feature.data.repository.FakeWeatherAppRepository
5 | import com.weather.app.domain.model.City
6 | import com.weather.app.domain.use_case.DeleteCity
7 | import kotlinx.coroutines.flow.first
8 | import kotlinx.coroutines.runBlocking
9 | import org.junit.Before
10 | import org.junit.Test
11 |
12 | class DeleteCityTest {
13 |
14 | private lateinit var deleteCity: DeleteCity
15 | private lateinit var fakeRepository: FakeWeatherAppRepository
16 |
17 | @Before
18 | fun setUp() {
19 | fakeRepository =
20 | FakeWeatherAppRepository()
21 | deleteCity = DeleteCity(fakeRepository)
22 |
23 | }
24 |
25 | @Test
26 | fun addCityOffline_ReturnSuccess() = runBlocking {
27 | val city =
28 | City(id = "1", localizedName = "Cairo", country = "Egypt", administrativeArea = "CA")
29 |
30 | fakeRepository.addCityOffline(city = city)
31 |
32 | val result = fakeRepository.getCities().first()
33 | assertThat(result.size).isEqualTo(1)
34 |
35 | deleteCity(city)
36 | val resultAfterDelete = fakeRepository.getCities().first()
37 | assertThat(resultAfterDelete.size).isEqualTo(0)
38 |
39 |
40 | }
41 |
42 |
43 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/domain/use_case/GetCurrentConditionsTest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.domain.use_case
2 |
3 | import com.google.common.truth.Truth.assertThat
4 | import com.squareup.moshi.Moshi
5 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
6 | import com.weather.app.app_feature.data.repository.FakeWeatherAppRepository
7 | import com.weather.app.app_feature.responses.MockWebServerResponses
8 | import com.weather.app.data.data_source.remote.RetrofitService
9 | import com.weather.app.domain.use_case.GetCurrentConditions
10 | import kotlinx.coroutines.flow.toList
11 | import kotlinx.coroutines.runBlocking
12 | import okhttp3.HttpUrl
13 | import okhttp3.mockwebserver.MockResponse
14 | import okhttp3.mockwebserver.MockWebServer
15 | import org.junit.After
16 | import org.junit.Before
17 | import org.junit.Test
18 | import retrofit2.Retrofit
19 | import retrofit2.converter.moshi.MoshiConverterFactory
20 | import java.net.HttpURLConnection
21 |
22 | class GetCurrentConditionsTest {
23 |
24 | private lateinit var getCurrentConditions: GetCurrentConditions
25 | private lateinit var fakeRepository: FakeWeatherAppRepository
26 | private lateinit var mockWebServer: MockWebServer
27 | private lateinit var baseUrl: HttpUrl
28 | private lateinit var retrofitService: RetrofitService
29 |
30 | @Before
31 | fun setUp() {
32 | mockWebServer = MockWebServer()
33 | mockWebServer.start()
34 | baseUrl = mockWebServer.url("currentconditions/v1/")
35 | retrofitService = Retrofit.Builder()
36 | .baseUrl(baseUrl)
37 | .addConverterFactory(
38 | MoshiConverterFactory.create(
39 | Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
40 | )
41 | )
42 | .build()
43 | .create(RetrofitService::class.java)
44 | fakeRepository =
45 | FakeWeatherAppRepository(retrofitService)
46 | getCurrentConditions = GetCurrentConditions(fakeRepository)
47 |
48 | }
49 |
50 | @After
51 | fun tearDown() {
52 | mockWebServer.shutdown()
53 | }
54 |
55 | @Test
56 | fun callCurrentConditions_ReturnSuccess() = runBlocking {
57 | mockWebServer.enqueue(
58 | MockResponse()
59 | .setResponseCode(HttpURLConnection.HTTP_OK)
60 | .setBody(MockWebServerResponses.currentConditions)
61 | )
62 |
63 | val result = getCurrentConditions.invoke("").toList()
64 |
65 | assertThat(result[0].loading).isTrue()
66 | val hourlyForecasts = result[1].data
67 | assertThat(hourlyForecasts?.get(0)?.precipitationType).isEqualTo("Rain")
68 | assertThat(hourlyForecasts?.get(0)?.weatherIcon).isEqualTo(3)
69 | assertThat(hourlyForecasts).isNotNull()
70 | assertThat(hourlyForecasts!!.size).isEqualTo(2)
71 |
72 | }
73 |
74 | @Test
75 | fun callCurrentConditions_ReturnHttpError() = runBlocking {
76 | mockWebServer.enqueue(
77 | MockResponse()
78 | .setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST)
79 | .setBody("{}")
80 | )
81 |
82 | val result = getCurrentConditions.invoke("").toList()
83 |
84 | assertThat(result[0].loading).isTrue()
85 | val error = result[1].error
86 | assertThat(error).isNotNull()
87 |
88 | }
89 |
90 |
91 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/domain/use_case/GetDailyForecastsTest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.domain.use_case
2 |
3 | import com.google.common.truth.Truth.assertThat
4 | import com.squareup.moshi.Moshi
5 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
6 | import com.weather.app.app_feature.data.repository.FakeWeatherAppRepository
7 | import com.weather.app.app_feature.responses.MockWebServerResponses
8 | import com.weather.app.data.data_source.remote.RetrofitService
9 | import com.weather.app.domain.use_case.GetDailyForecasts
10 | import kotlinx.coroutines.flow.toList
11 | import kotlinx.coroutines.runBlocking
12 | import okhttp3.HttpUrl
13 | import okhttp3.mockwebserver.MockResponse
14 | import okhttp3.mockwebserver.MockWebServer
15 | import org.junit.After
16 | import org.junit.Before
17 | import org.junit.Test
18 | import retrofit2.Retrofit
19 | import retrofit2.converter.moshi.MoshiConverterFactory
20 | import java.net.HttpURLConnection
21 |
22 | class GetDailyForecastsTest {
23 |
24 | private lateinit var getDailyForecasts: GetDailyForecasts
25 | private lateinit var fakeRepository: FakeWeatherAppRepository
26 | private lateinit var mockWebServer: MockWebServer
27 | private lateinit var baseUrl: HttpUrl
28 | private lateinit var retrofitService: RetrofitService
29 |
30 | @Before
31 | fun setUp() {
32 | mockWebServer = MockWebServer()
33 | mockWebServer.start()
34 | baseUrl = mockWebServer.url("forecasts/v1/daily/5day/")
35 | retrofitService = Retrofit.Builder()
36 | .baseUrl(baseUrl)
37 | .addConverterFactory(
38 | MoshiConverterFactory.create(
39 | Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
40 | )
41 | )
42 | .build()
43 | .create(RetrofitService::class.java)
44 | fakeRepository =
45 | FakeWeatherAppRepository(retrofitService)
46 | getDailyForecasts = GetDailyForecasts(fakeRepository)
47 |
48 | }
49 |
50 | @After
51 | fun tearDown() {
52 | mockWebServer.shutdown()
53 | }
54 |
55 | @Test
56 | fun callDailyForecasts_ReturnSuccess() = runBlocking {
57 | mockWebServer.enqueue(
58 | MockResponse()
59 | .setResponseCode(HttpURLConnection.HTTP_OK)
60 | .setBody(MockWebServerResponses.dailyForecastResponse)
61 | )
62 |
63 | val result = getDailyForecasts.invoke("").toList()
64 |
65 | assertThat(result[0].loading).isTrue()
66 | val hourlyForecasts = result[1].data
67 | assertThat(hourlyForecasts?.get(0)?.temperature?.minimum?.value).isEqualTo(20)
68 | assertThat(hourlyForecasts?.get(0)?.temperature?.maximum?.value).isEqualTo(30)
69 | assertThat(hourlyForecasts).isNotNull()
70 | assertThat(hourlyForecasts!!.size).isEqualTo(3)
71 |
72 | }
73 |
74 | @Test
75 | fun callDailyForecasts_ReturnHttpError() = runBlocking {
76 | mockWebServer.enqueue(
77 | MockResponse()
78 | .setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST)
79 | .setBody("{}")
80 | )
81 |
82 | val result = getDailyForecasts.invoke("").toList()
83 |
84 | assertThat(result[0].loading).isTrue()
85 | val error = result[1].error
86 | assertThat(error).isNotNull()
87 |
88 | }
89 |
90 |
91 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/domain/use_case/GetHourlyForecastsTest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.domain.use_case
2 |
3 | import com.google.common.truth.Truth.assertThat
4 | import com.squareup.moshi.Moshi
5 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
6 | import com.weather.app.app_feature.data.repository.FakeWeatherAppRepository
7 | import com.weather.app.app_feature.responses.MockWebServerResponses
8 | import com.weather.app.data.data_source.remote.RetrofitService
9 | import com.weather.app.domain.use_case.GetHourlyForecasts
10 | import kotlinx.coroutines.flow.toList
11 | import kotlinx.coroutines.runBlocking
12 | import okhttp3.HttpUrl
13 | import okhttp3.mockwebserver.MockResponse
14 | import okhttp3.mockwebserver.MockWebServer
15 | import org.junit.After
16 | import org.junit.Before
17 | import org.junit.Test
18 | import retrofit2.Retrofit
19 | import retrofit2.converter.moshi.MoshiConverterFactory
20 | import java.net.HttpURLConnection
21 |
22 | class GetHourlyForecastsTest {
23 |
24 | private lateinit var getHourlyForecasts: GetHourlyForecasts
25 | private lateinit var fakeRepository: FakeWeatherAppRepository
26 | private lateinit var mockWebServer: MockWebServer
27 | private lateinit var baseUrl: HttpUrl
28 | private lateinit var retrofitService: RetrofitService
29 |
30 | @Before
31 | fun setUp() {
32 | mockWebServer = MockWebServer()
33 | mockWebServer.start()
34 | baseUrl = mockWebServer.url("forecasts/v1/hourly/12hour/")
35 | retrofitService = Retrofit.Builder()
36 | .baseUrl(baseUrl)
37 | .addConverterFactory(
38 | MoshiConverterFactory.create(
39 | Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
40 | )
41 | )
42 | .build()
43 | .create(RetrofitService::class.java)
44 | fakeRepository =
45 | FakeWeatherAppRepository(retrofitService)
46 | getHourlyForecasts = GetHourlyForecasts(fakeRepository)
47 |
48 | }
49 |
50 | @After
51 | fun tearDown() {
52 | mockWebServer.shutdown()
53 | }
54 |
55 | @Test
56 | fun callHourlyForecasts_ReturnSuccess() = runBlocking {
57 | mockWebServer.enqueue(
58 | MockResponse()
59 | .setResponseCode(HttpURLConnection.HTTP_OK)
60 | .setBody(MockWebServerResponses.hourlyForecastData)
61 | )
62 |
63 | val result = getHourlyForecasts.invoke("").toList()
64 |
65 | assertThat(result[0].loading).isTrue()
66 | val hourlyForecasts = result[1].data
67 | assertThat(hourlyForecasts?.get(0)?.temperature?.value).isEqualTo(25)
68 | assertThat(hourlyForecasts?.get(0)?.temperature?.unit).isEqualTo("Celsius")
69 | assertThat(hourlyForecasts).isNotNull()
70 | assertThat(hourlyForecasts!!.size).isEqualTo(3)
71 |
72 | }
73 |
74 | @Test
75 | fun callHourlyForecasts_ReturnHttpError() = runBlocking {
76 | mockWebServer.enqueue(
77 | MockResponse()
78 | .setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST)
79 | .setBody("{}")
80 | )
81 |
82 | val result = getHourlyForecasts.invoke("").toList()
83 |
84 | assertThat(result[0].loading).isTrue()
85 | val error = result[1].error
86 | assertThat(error).isNotNull()
87 |
88 | }
89 |
90 |
91 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/domain/use_case/GetSearchResultsTest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.domain.use_case
2 |
3 | import com.google.common.truth.Truth.assertThat
4 | import com.squareup.moshi.Moshi
5 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
6 | import com.weather.app.app_feature.data.repository.FakeWeatherAppRepository
7 | import com.weather.app.app_feature.responses.MockWebServerResponses
8 | import com.weather.app.data.data_source.remote.RetrofitService
9 | import com.weather.app.domain.use_case.GetSearchResults
10 | import kotlinx.coroutines.flow.toList
11 | import kotlinx.coroutines.runBlocking
12 | import okhttp3.HttpUrl
13 | import okhttp3.mockwebserver.MockResponse
14 | import okhttp3.mockwebserver.MockWebServer
15 | import org.junit.After
16 | import org.junit.Before
17 | import org.junit.Test
18 | import retrofit2.Retrofit
19 | import retrofit2.converter.moshi.MoshiConverterFactory
20 | import java.net.HttpURLConnection
21 |
22 | class GetSearchResultsTest {
23 |
24 | private lateinit var getSearchResults: GetSearchResults
25 | private lateinit var fakeRepository: FakeWeatherAppRepository
26 | private lateinit var mockWebServer: MockWebServer
27 | private lateinit var baseUrl: HttpUrl
28 | private lateinit var retrofitService: RetrofitService
29 |
30 | @Before
31 | fun setUp() {
32 | mockWebServer = MockWebServer()
33 | mockWebServer.start()
34 | baseUrl = mockWebServer.url("locations/v1/cities/autocomplete/")
35 | retrofitService = Retrofit.Builder()
36 | .baseUrl(baseUrl)
37 | .addConverterFactory(
38 | MoshiConverterFactory.create(
39 | Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
40 | )
41 | )
42 | .build()
43 | .create(RetrofitService::class.java)
44 | fakeRepository =
45 | FakeWeatherAppRepository(retrofitService)
46 | getSearchResults = GetSearchResults(fakeRepository)
47 |
48 | }
49 |
50 | @After
51 | fun tearDown() {
52 | mockWebServer.shutdown()
53 | }
54 |
55 | @Test
56 | fun callGetResults_ReturnSuccess() = runBlocking {
57 | mockWebServer.enqueue(
58 | MockResponse()
59 | .setResponseCode(HttpURLConnection.HTTP_OK)
60 | .setBody(MockWebServerResponses.searchResults)
61 | )
62 |
63 | val result = getSearchResults.invoke("").toList()
64 |
65 | assertThat(result[0].loading).isTrue()
66 | val cities = result[1].data
67 | assertThat(cities?.get(0)?.localizedName?.lowercase()).isEqualTo("Cairo".lowercase())
68 | assertThat(cities).isNotNull()
69 | assertThat(cities!!.size).isEqualTo(2)
70 |
71 | }
72 |
73 | @Test
74 | fun callGetResults_ReturnHttpError() = runBlocking {
75 | mockWebServer.enqueue(
76 | MockResponse()
77 | .setResponseCode(HttpURLConnection.HTTP_BAD_REQUEST)
78 | .setBody("{}")
79 | )
80 |
81 | val result = getSearchResults.invoke("").toList()
82 |
83 | assertThat(result[0].loading).isTrue()
84 | val error = result[1].error
85 | assertThat(error).isNotNull()
86 |
87 | }
88 |
89 |
90 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/presentation/home_screen/HomeScreenViewModelTest.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.presentation.home_screen
2 |
3 | import app.cash.turbine.test
4 | import com.google.common.truth.Truth.assertThat
5 | import com.weather.app.app_feature.MainDispatcherRule
6 | import com.weather.app.data.data_source.local.WeatherDataStore
7 | import com.weather.app.data.data_source.remote.response.Temperature
8 | import com.weather.app.data.data_source.remote.response.TemperatureUnit
9 | import com.weather.app.data.data_source.remote.response.WeatherData
10 | import com.weather.app.data.repository.AppRepositoryImpl
11 | import com.weather.app.domain.DataState
12 | import com.weather.app.domain.use_case.AppUseCases
13 | import com.weather.app.domain.use_case.GetCurrentConditions
14 | import com.weather.app.presentation.home_screen.HomeScreenEvent
15 | import com.weather.app.presentation.home_screen.HomeScreenState
16 | import com.weather.app.presentation.home_screen.HomeScreenViewModel
17 | import com.weather.app.util.ConnectivityManager
18 | import io.mockk.coEvery
19 | import io.mockk.coVerify
20 | import io.mockk.every
21 | import io.mockk.impl.annotations.MockK
22 | import io.mockk.junit4.MockKRule
23 | import kotlinx.coroutines.flow.flow
24 | import kotlinx.coroutines.flow.flowOf
25 | import kotlinx.coroutines.runBlocking
26 | import kotlinx.coroutines.test.runTest
27 | import org.junit.Before
28 | import org.junit.Rule
29 | import org.junit.Test
30 |
31 |
32 | class HomeScreenViewModelTest {
33 | @get:Rule(order = 0)
34 | val mockkRule = MockKRule(this)
35 |
36 | @get:Rule(order = 1)
37 | val mainDispatcherRule = MainDispatcherRule()
38 |
39 | private lateinit var homeScreenViewModel: HomeScreenViewModel
40 |
41 |
42 | @MockK
43 | lateinit var appUseCases: AppUseCases
44 |
45 |
46 | @MockK
47 | lateinit var connectivityManager: ConnectivityManager
48 |
49 | @MockK
50 | lateinit var dataStore: WeatherDataStore
51 |
52 |
53 | @MockK
54 | lateinit var mockAppRepositoryImpl: AppRepositoryImpl
55 |
56 |
57 | @Before
58 | fun setUp() {
59 | every {
60 | dataStore.getDarkThemePrefs()
61 | } returns flowOf(true)
62 |
63 | every {
64 | dataStore.getCityPrefs()
65 | } returns flowOf("Cairo-1")
66 |
67 | every {
68 | connectivityManager.isNetworkAvailable.value
69 | } returns true
70 |
71 | every {
72 | appUseCases.getCurrentConditions
73 | } returns GetCurrentConditions(mockAppRepositoryImpl)
74 |
75 | homeScreenViewModel = HomeScreenViewModel(appUseCases, connectivityManager, dataStore)
76 |
77 | }
78 |
79 | @Test
80 | fun testGetTheme_ReturnTrue() = runBlocking {
81 | every {
82 | dataStore.getDarkThemePrefs()
83 | } returns flowOf(true)
84 |
85 | dataStore.getDarkThemePrefs().test {
86 | val item = awaitItem()
87 | awaitComplete()
88 | assertThat(item).isTrue()
89 | }
90 |
91 | }
92 |
93 | @Test
94 | fun testGetTheme_ReturnFalse() = runBlocking {
95 | every {
96 | dataStore.getDarkThemePrefs()
97 | } returns flowOf(false)
98 |
99 | dataStore.getDarkThemePrefs().test {
100 | val item = awaitItem()
101 | awaitComplete()
102 | assertThat(item).isFalse()
103 | }
104 | }
105 |
106 | @Test
107 | fun testGetCurrentConditions_NoInternet_ReturnFalse() = runBlocking {
108 | //Given
109 | every {
110 | connectivityManager.isNetworkAvailable.value
111 | } returns false
112 |
113 | homeScreenViewModel.eventFlow.test {
114 | //When
115 | homeScreenViewModel.onEvent(HomeScreenEvent.GetCurrentConditions("1"))
116 | val item = awaitItem()
117 | //Then
118 | assertThat(item).isEqualTo(
119 | HomeScreenViewModel.UiEvent.ShowSnackbar("No network available")
120 | )
121 |
122 | }
123 | }
124 |
125 | @Test
126 | fun testGetCurrentConditions_HasInternet_ReturnTrue() = runTest {
127 | every {
128 | connectivityManager.isNetworkAvailable.value
129 | } returns true
130 |
131 | //Given
132 | val sampleWeatherData = WeatherData(
133 | localObservationDateTime = "2023-12-03T12:36:00+02:00",
134 | epochTime = 1701599760,
135 | weatherText = "Mostly cloudy",
136 | weatherIcon = 40,
137 | hasPrecipitation = false,
138 | precipitationType = null,
139 | isDayTime = false,
140 | temperature = Temperature(
141 | metric = TemperatureUnit(23.6, "C", 17),
142 | imperial = TemperatureUnit(75.0, "F", 18)
143 | ),
144 | mobileLink = "http://www.accuweather.com/en/eg/cairo/127164/current-weather/127164?lang=en-us",
145 | link = "http://www.accuweather.com/en/eg/cairo/127164/current-weather/127164?lang=en-us"
146 | )
147 |
148 | //When
149 | coEvery {
150 | appUseCases.getCurrentConditions.invoke("1")
151 | } returns flow {
152 | emit(DataState.loading())
153 | emit(DataState(data = listOf(sampleWeatherData)))
154 | }
155 |
156 | homeScreenViewModel.onEvent(HomeScreenEvent.GetCurrentConditions("1"))
157 |
158 | coVerify {
159 | appUseCases.getCurrentConditions.invoke("1")
160 | }
161 |
162 | //Then
163 | assertThat(homeScreenViewModel.state.value).isEqualTo(
164 | HomeScreenState.Loading
165 | )
166 | homeScreenViewModel.state.test {
167 | val item = awaitItem()
168 | assertThat(item).isEqualTo(
169 | HomeScreenState.Success.Weather(
170 | data = listOf(
171 | sampleWeatherData
172 | )
173 | )
174 | )
175 | }
176 |
177 | }
178 |
179 |
180 | @Test
181 | fun testGetCurrentConditions_HasInternet_ReturnError() = runTest {
182 | //Given
183 | every {
184 | connectivityManager.isNetworkAvailable.value
185 | } returns true
186 |
187 | coEvery {
188 | appUseCases.getCurrentConditions.invoke("1")
189 | } returns flow {
190 | emit(DataState.loading())
191 | emit(DataState(error = "error"))
192 | }
193 |
194 | homeScreenViewModel.eventFlow.test {
195 | //When
196 | homeScreenViewModel.onEvent(HomeScreenEvent.GetCurrentConditions("1"))
197 |
198 | coVerify {
199 | appUseCases.getCurrentConditions.invoke("1")
200 | }
201 |
202 | //Then
203 | val item = awaitItem()
204 | assertThat(item).isEqualTo(
205 | HomeScreenViewModel.UiEvent.ShowSnackbar("error")
206 | )
207 | }
208 |
209 | }
210 |
211 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/weather/app/app_feature/responses/MockWebServerResponses.kt:
--------------------------------------------------------------------------------
1 | package com.weather.app.app_feature.responses
2 |
3 | object MockWebServerResponses {
4 | const val searchResults = "[\n" +
5 | " {\n" +
6 | " \"Key\": \"1\",\n" +
7 | " \"LocalizedName\": \"Cairo\",\n" +
8 | " \"Country\": {\n" +
9 | " \"Key\": \"EG\",\n" +
10 | " \"LocalizedName\": \"Egypt\"\n" +
11 | " },\n" +
12 | " \"AdministrativeArea\": {\n" +
13 | " \"Key\": \"CAI\",\n" +
14 | " \"LocalizedName\": \"Cairo\"\n" +
15 | " }\n" +
16 | " },\n" +
17 | " {\n" +
18 | " \"Key\": \"2\",\n" +
19 | " \"LocalizedName\": \"Alex\",\n" +
20 | " \"Country\": {\n" +
21 | " \"Key\": \"EG\",\n" +
22 | " \"LocalizedName\": \"Egypt\"\n" +
23 | " },\n" +
24 | " \"AdministrativeArea\": {\n" +
25 | " \"Key\": \"ALX\",\n" +
26 | " \"LocalizedName\": \"Alex\"\n" +
27 | " }\n" +
28 | " }\n" +
29 | "]\n"
30 |
31 |
32 | const val hourlyForecastData = "[\n" +
33 | " {\n" +
34 | " \"DateTime\": \"2023-12-07T12:00:00\",\n" +
35 | " \"IconPhrase\": \"Partly Cloudy\",\n" +
36 | " \"WeatherIcon\": 3,\n" +
37 | " \"Temperature\": {\n" +
38 | " \"Value\": 25,\n" +
39 | " \"Unit\": \"Celsius\"\n" +
40 | " },\n" +
41 | " \"Link\": \"https://example.com/hourly/1\"\n" +
42 | " },\n" +
43 | " {\n" +
44 | " \"DateTime\": \"2023-12-07T15:00:00\",\n" +
45 | " \"IconPhrase\": \"Sunny\",\n" +
46 | " \"WeatherIcon\": 1,\n" +
47 | " \"Temperature\": {\n" +
48 | " \"Value\": 28,\n" +
49 | " \"Unit\": \"Celsius\"\n" +
50 | " },\n" +
51 | " \"Link\": \"https://example.com/hourly/2\"\n" +
52 | " },\n" +
53 | " {\n" +
54 | " \"DateTime\": \"2023-12-07T18:00:00\",\n" +
55 | " \"IconPhrase\": \"Cloudy\",\n" +
56 | " \"WeatherIcon\": 4,\n" +
57 | " \"Temperature\": {\n" +
58 | " \"Value\": 22,\n" +
59 | " \"Unit\": \"Celsius\"\n" +
60 | " },\n" +
61 | " \"Link\": \"https://example.com/hourly/3\"\n" +
62 | " }\n" +
63 | "]\n"
64 |
65 | const val dailyForecastResponse = "{\n" +
66 | " \"DailyForecasts\": [\n" +
67 | " {\n" +
68 | " \"Date\": \"2023-12-07\",\n" +
69 | " \"Temperature\": {\n" +
70 | " \"Minimum\": {\n" +
71 | " \"Value\": 20,\n" +
72 | " \"Unit\": \"Celsius\"\n" +
73 | " },\n" +
74 | " \"Maximum\": {\n" +
75 | " \"Value\": 30,\n" +
76 | " \"Unit\": \"Celsius\"\n" +
77 | " }\n" +
78 | " },\n" +
79 | " \"Day\": {\n" +
80 | " \"Icon\": 2,\n" +
81 | " \"IconPhrase\": \"Cloudy\"\n" +
82 | " },\n" +
83 | " \"Link\": \"https://example.com/daily/1\"\n" +
84 | " },\n" +
85 | " {\n" +
86 | " \"Date\": \"2023-12-08\",\n" +
87 | " \"Temperature\": {\n" +
88 | " \"Minimum\": {\n" +
89 | " \"Value\": 18,\n" +
90 | " \"Unit\": \"Celsius\"\n" +
91 | " },\n" +
92 | " \"Maximum\": {\n" +
93 | " \"Value\": 28,\n" +
94 | " \"Unit\": \"Celsius\"\n" +
95 | " }\n" +
96 | " },\n" +
97 | " \"Day\": {\n" +
98 | " \"Icon\": 1,\n" +
99 | " \"IconPhrase\": \"Sunny\"\n" +
100 | " },\n" +
101 | " \"Link\": \"https://example.com/daily/2\"\n" +
102 | " },\n" +
103 | " {\n" +
104 | " \"Date\": \"2023-12-09\",\n" +
105 | " \"Temperature\": {\n" +
106 | " \"Minimum\": {\n" +
107 | " \"Value\": 22,\n" +
108 | " \"Unit\": \"Celsius\"\n" +
109 | " },\n" +
110 | " \"Maximum\": {\n" +
111 | " \"Value\": 32,\n" +
112 | " \"Unit\": \"Celsius\"\n" +
113 | " }\n" +
114 | " },\n" +
115 | " \"Day\": {\n" +
116 | " \"Icon\": 3,\n" +
117 | " \"IconPhrase\": \"Partly Cloudy\"\n" +
118 | " },\n" +
119 | " \"Link\": \"https://example.com/daily/3\"\n" +
120 | " }\n" +
121 | " ]\n" +
122 | "}\n"
123 |
124 | const val currentConditions = "[\n" +
125 | " {\n" +
126 | " \"LocalObservationDateTime\": \"2023-12-07T13:45:00+02:00\",\n" +
127 | " \"EpochTime\": 1670496300,\n" +
128 | " \"WeatherText\": \"Partly Cloudy\",\n" +
129 | " \"WeatherIcon\": 3,\n" +
130 | " \"HasPrecipitation\": true,\n" +
131 | " \"PrecipitationType\": \"Rain\",\n" +
132 | " \"IsDayTime\": true,\n" +
133 | " \"Temperature\": {\n" +
134 | " \"Metric\": {\n" +
135 | " \"Value\": 25.5,\n" +
136 | " \"Unit\": \"Celsius\",\n" +
137 | " \"UnitType\": 17\n" +
138 | " },\n" +
139 | " \"Imperial\": {\n" +
140 | " \"Value\": 77.9,\n" +
141 | " \"Unit\": \"Fahrenheit\",\n" +
142 | " \"UnitType\": 18\n" +
143 | " }\n" +
144 | " },\n" +
145 | " \"MobileLink\": \"https://example.com/weather/mobile/1\",\n" +
146 | " \"Link\": \"https://example.com/weather/1\"\n" +
147 | " },\n" +
148 | " {\n" +
149 | " \"LocalObservationDateTime\": \"2023-12-07T16:30:00+02:00\",\n" +
150 | " \"EpochTime\": 1670507400,\n" +
151 | " \"WeatherText\": \"Clear\",\n" +
152 | " \"WeatherIcon\": 1,\n" +
153 | " \"HasPrecipitation\": false,\n" +
154 | " \"PrecipitationType\": null,\n" +
155 | " \"IsDayTime\": true,\n" +
156 | " \"Temperature\": {\n" +
157 | " \"Metric\": {\n" +
158 | " \"Value\": 28.2,\n" +
159 | " \"Unit\": \"Celsius\",\n" +
160 | " \"UnitType\": 17\n" +
161 | " },\n" +
162 | " \"Imperial\": {\n" +
163 | " \"Value\": 82.8,\n" +
164 | " \"Unit\": \"Fahrenheit\",\n" +
165 | " \"UnitType\": 18\n" +
166 | " }\n" +
167 | " },\n" +
168 | " \"MobileLink\": \"https://example.com/weather/mobile/2\",\n" +
169 | " \"Link\": \"https://example.com/weather/2\"\n" +
170 | " }\n" +
171 | "]\n"
172 | }
173 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | plugins {
3 | id("com.android.library") version "8.1.2" apply false
4 | id("com.android.application") version "8.1.2" apply false
5 | id("org.jetbrains.kotlin.android") version "1.9.10" apply false
6 | id("com.google.dagger.hilt.android") version "2.48.1" apply false
7 | id("com.google.devtools.ksp") version "1.9.10-1.0.13" apply false
8 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abualgait/CleanArchitectureWeatherApp/60c911a1bf58bece66dc4d79cb2c89add6c047e8/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 |
16 | rootProject.name = "WeatherApp"
17 | include(":app")
18 |
--------------------------------------------------------------------------------