├── .gitignore ├── LICENSE ├── README.md ├── img └── workshop_logo.png └── weatherapp ├── LICENSE ├── app ├── .gitignore ├── build.gradle ├── schemas │ └── fr.ekito.myweatherapp.data.datasource.room.WeatherDatabase │ │ └── 1.json └── src │ ├── androidTest │ └── java │ │ └── fr │ │ └── ekito │ │ └── myweatherapp │ │ ├── WeatherDAOTest.kt │ │ ├── WeatherRepositoryTest.kt │ │ └── room_test_modules.kt │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ ├── json │ │ │ ├── geocode_berlin.json │ │ │ ├── geocode_london.json │ │ │ ├── geocode_madrid.json │ │ │ ├── geocode_paris.json │ │ │ ├── geocode_toulouse.json │ │ │ ├── weather_berlin.json │ │ │ ├── weather_london.json │ │ │ ├── weather_madrid.json │ │ │ ├── weather_paris.json │ │ │ └── weather_toulouse.json │ │ └── koin.properties │ ├── kotlin │ │ └── fr │ │ │ └── ekito │ │ │ └── myweatherapp │ │ │ ├── MainApplication.kt │ │ │ ├── data │ │ │ ├── datasource │ │ │ │ ├── room │ │ │ │ │ ├── Converters.kt │ │ │ │ │ ├── WeatherDAO.kt │ │ │ │ │ ├── WeatherDatabase.kt │ │ │ │ │ └── WeatherEntity.kt │ │ │ │ └── webservice │ │ │ │ │ ├── WeatherWebDatasource.kt │ │ │ │ │ ├── json │ │ │ │ │ ├── geocode │ │ │ │ │ │ ├── AddressComponent.kt │ │ │ │ │ │ ├── Geocode.kt │ │ │ │ │ │ ├── GeocodeExt.kt │ │ │ │ │ │ ├── Geometry.kt │ │ │ │ │ │ ├── Location.kt │ │ │ │ │ │ ├── Northeast.kt │ │ │ │ │ │ ├── Result.kt │ │ │ │ │ │ ├── Southwest.kt │ │ │ │ │ │ └── Viewport.kt │ │ │ │ │ └── weather │ │ │ │ │ │ ├── Avewind.kt │ │ │ │ │ │ ├── Date.kt │ │ │ │ │ │ ├── Features.kt │ │ │ │ │ │ ├── Forecast.kt │ │ │ │ │ │ ├── Forecastday.kt │ │ │ │ │ │ ├── Forecastday_.kt │ │ │ │ │ │ ├── High.kt │ │ │ │ │ │ ├── Low.kt │ │ │ │ │ │ ├── Maxwind.kt │ │ │ │ │ │ ├── QpfAllday.kt │ │ │ │ │ │ ├── QpfDay.kt │ │ │ │ │ │ ├── QpfNight.kt │ │ │ │ │ │ ├── Response.kt │ │ │ │ │ │ ├── Simpleforecast.kt │ │ │ │ │ │ ├── SnowAllday.kt │ │ │ │ │ │ ├── SnowDay.kt │ │ │ │ │ │ ├── SnowNight.kt │ │ │ │ │ │ ├── TxtForecast.kt │ │ │ │ │ │ ├── Weather.kt │ │ │ │ │ │ └── WeatherExt.kt │ │ │ │ │ └── local │ │ │ │ │ ├── AndroidJsonReader.kt │ │ │ │ │ ├── BaseReader.kt │ │ │ │ │ ├── JavaReader.kt │ │ │ │ │ ├── JsonReader.kt │ │ │ │ │ └── LocalFileDataSource.kt │ │ │ └── repository │ │ │ │ └── WeatherRepository.kt │ │ │ ├── di │ │ │ ├── app_module.kt │ │ │ ├── local_datasource_module.kt │ │ │ └── remote_datasource_module.kt │ │ │ ├── domain │ │ │ ├── DailyForecastModel.kt │ │ │ └── WeatherCode.kt │ │ │ ├── util │ │ │ ├── ext │ │ │ │ └── FragmentActivityExt.kt │ │ │ ├── mvp │ │ │ │ ├── BasePresenter.kt │ │ │ │ ├── BaseView.kt │ │ │ │ └── RxPresenter.kt │ │ │ ├── mvvm │ │ │ │ ├── RxViewModel.kt │ │ │ │ └── SingleLiveEvent.kt │ │ │ └── rx │ │ │ │ ├── ApplicationSchedulerProvider.kt │ │ │ │ └── SchedulerProvider.kt │ │ │ └── view │ │ │ ├── Events.kt │ │ │ ├── IntentArguments.kt │ │ │ ├── States.kt │ │ │ ├── detail │ │ │ ├── DetailActivity.kt │ │ │ └── DetailViewModel.kt │ │ │ ├── splash │ │ │ ├── SplashActivity.kt │ │ │ └── SplashViewModel.kt │ │ │ └── weather │ │ │ ├── WeatherActivity.kt │ │ │ ├── WeatherHeaderFragment.kt │ │ │ ├── WeatherListFragment.kt │ │ │ ├── WeatherViewModel.kt │ │ │ └── list │ │ │ ├── WeatherItem.kt │ │ │ └── WeatherListAdapter.kt │ └── res │ │ ├── anim │ │ └── infinite_blinking_animation.xml │ │ ├── drawable │ │ ├── ic_edit_black_24dp.xml │ │ ├── ic_edit_location_black_24dp.xml │ │ ├── ic_location_on_black_24dp.xml │ │ └── ic_search_black_24dp.xml │ │ ├── font │ │ ├── indieflower.ttf │ │ └── opensans_regular.ttf │ │ ├── layout │ │ ├── activity_detail.xml │ │ ├── activity_result.xml │ │ ├── activity_splash.xml │ │ ├── fragment_result_header.xml │ │ ├── fragment_result_list.xml │ │ └── item_weather.xml │ │ ├── menu │ │ └── menu_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ ├── java │ └── fr │ │ └── ekito │ │ └── myweatherapp │ │ ├── DryRunTest.kt │ │ ├── datasource │ │ └── WeatherRepositoryTest.kt │ │ ├── di │ │ └── test_modules.kt │ │ ├── mock │ │ ├── MockedData.kt │ │ ├── mvp │ │ │ ├── DetailPresenterMockTest.kt │ │ │ ├── SplashPresenterMockTest.kt │ │ │ ├── WeatherHeaderPresenterMockTest.kt │ │ │ └── WeatherListPresenterMockTest.kt │ │ └── mvvm │ │ │ ├── DetailViewModelMockTest.kt │ │ │ ├── SplashViewModelMockTest.kt │ │ │ └── WeatherViewModelMockTest.kt │ │ └── util │ │ ├── MockitoKotlinHelpers.kt │ │ └── TestSchedulerProvider.kt │ └── resources │ ├── json │ ├── geocode_berlin.json │ ├── geocode_london.json │ ├── geocode_madrid.json │ ├── geocode_paris.json │ ├── geocode_toulouse.json │ ├── weather_berlin.json │ ├── weather_london.json │ ├── weather_madrid.json │ ├── weather_paris.json │ └── weather_toulouse.json │ ├── koin.properties │ └── mockito-extensions │ └── org.mockito.plugins.MockMaker ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── versions.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.apk 2 | .idea/ 3 | *.iml 4 | .gradle 5 | local.properties 6 | /.idea/workspace.xml 7 | /.idea/libraries 8 | .DS_Store 9 | /build 10 | /captures 11 | .externalNativeBuild 12 | build/ 13 | 14 | 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android MVVM Arch Components with Coroutines 2 | -------------------------------------------------------------------------------- /img/workshop_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ekito/mvvm-coroutines/be37b060c9abe61717f26367e6957bd6e601dd64/img/workshop_logo.png -------------------------------------------------------------------------------- /weatherapp/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /weatherapp/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /weatherapp/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-kapt' 4 | apply plugin: 'kotlin-android-extensions' 5 | 6 | android { 7 | compileSdkVersion rootProject.ext.compileSdkVersion 8 | buildToolsVersion rootProject.ext.buildToolsVersion 9 | 10 | defaultConfig { 11 | minSdkVersion 21 12 | targetSdkVersion rootProject.ext.targetSdkVersion 13 | applicationId "koin.sampleapp" 14 | versionCode 1 15 | versionName "1.0" 16 | 17 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 18 | 19 | // used by Room, to test migrations 20 | javaCompileOptions { 21 | annotationProcessorOptions { 22 | arguments = ["room.schemaLocation": 23 | "$projectDir/schemas".toString()] 24 | } 25 | } 26 | } 27 | testOptions { 28 | execution 'ANDROID_TEST_ORCHESTRATOR' 29 | } 30 | buildTypes { 31 | release { 32 | minifyEnabled false 33 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 34 | } 35 | } 36 | sourceSets { 37 | main.java.srcDirs += 'src/main/kotlin' 38 | test.java.srcDirs += 'src/test/kotlin' 39 | 40 | // used by Room, to test migrations 41 | androidTest.assets.srcDirs += 42 | files("$projectDir/schemas".toString()) 43 | } 44 | } 45 | 46 | dependencies { 47 | implementation fileTree(dir: 'libs', include: ['*.jar']) 48 | 49 | // Android Support 50 | implementation "com.android.support:appcompat-v7:$supportLibraryVersion" 51 | implementation "com.android.support:design:$supportLibraryVersion" 52 | 53 | // Android Test 54 | testImplementation "junit:junit:$junit_version" 55 | testImplementation "org.mockito:mockito-core:$mockito_version" 56 | androidTestImplementation 'com.android.support.test:runner:1.0.1' 57 | androidTestUtil 'com.android.support.test:orchestrator:1.0.1' 58 | 59 | // Kotlin 60 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 61 | // Anko 62 | implementation "org.jetbrains.anko:anko-commons:$anko_version" 63 | // Koin 64 | implementation "org.koin:koin-android:$koin_version" 65 | implementation "org.koin:koin-android-architecture:$koin_version" 66 | testImplementation "org.koin:koin-test:$koin_version" 67 | androidTestImplementation "org.koin:koin-test:$koin_version" 68 | 69 | // ViewModel and LiveData 70 | implementation "android.arch.lifecycle:extensions:$androidArchitectureVersion" 71 | annotationProcessor "android.arch.lifecycle:compiler:$androidArchitectureVersion" 72 | testImplementation "android.arch.core:core-testing:$androidArchitectureVersion" 73 | 74 | // Room 75 | implementation "android.arch.persistence.room:runtime:$roomVersion" 76 | implementation "android.arch.persistence.room:rxjava2:$roomVersion" 77 | kapt "android.arch.persistence.room:compiler:$roomVersion" 78 | annotationProcessor "android.arch.persistence.room:compiler:$roomVersion" 79 | testImplementation "android.arch.persistence.room:testing:$roomVersion" 80 | 81 | // Networking 82 | implementation "com.squareup.retrofit2:retrofit:$retrofit_version" 83 | implementation "com.squareup.retrofit2:converter-gson:$retrofit_version" 84 | implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version" 85 | implementation "com.squareup.okhttp3:okhttp:$okhttp_version" 86 | implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_version" 87 | 88 | // Rx 89 | implementation "io.reactivex.rxjava2:rxjava:$rxjava_version" 90 | implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' 91 | implementation 'com.android.support.constraint:constraint-layout:1.0.2' 92 | 93 | // Coroutines 94 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5' 95 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:0.22.5" 96 | implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-experimental-adapter:1.0.0' 97 | 98 | // UI 99 | implementation 'com.joanzapata.iconify:android-iconify-weathericons:2.2.2' 100 | 101 | // Gson 102 | implementation 'com.google.code.gson:gson:2.8.2' 103 | } 104 | 105 | -------------------------------------------------------------------------------- /weatherapp/app/schemas/fr.ekito.myweatherapp.data.datasource.room.WeatherDatabase/1.json: -------------------------------------------------------------------------------- 1 | { 2 | "formatVersion": 1, 3 | "database": { 4 | "version": 1, 5 | "identityHash": "4bf9c0b54687f2551fead413ed964d04", 6 | "entities": [ 7 | { 8 | "tableName": "weather", 9 | "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `location` TEXT NOT NULL, `day` TEXT NOT NULL, `shortText` TEXT NOT NULL, `fullText` TEXT NOT NULL, `iconUrl` TEXT NOT NULL, `icon` TEXT NOT NULL, `temp_low` TEXT NOT NULL, `temp_high` TEXT NOT NULL, `wind_kph` INTEGER NOT NULL, `wind_dir` TEXT NOT NULL, `humidity` INTEGER NOT NULL, `date` INTEGER NOT NULL, PRIMARY KEY(`id`))", 10 | "fields": [ 11 | { 12 | "fieldPath": "id", 13 | "columnName": "id", 14 | "affinity": "TEXT", 15 | "notNull": true 16 | }, 17 | { 18 | "fieldPath": "location", 19 | "columnName": "location", 20 | "affinity": "TEXT", 21 | "notNull": true 22 | }, 23 | { 24 | "fieldPath": "day", 25 | "columnName": "day", 26 | "affinity": "TEXT", 27 | "notNull": true 28 | }, 29 | { 30 | "fieldPath": "shortText", 31 | "columnName": "shortText", 32 | "affinity": "TEXT", 33 | "notNull": true 34 | }, 35 | { 36 | "fieldPath": "fullText", 37 | "columnName": "fullText", 38 | "affinity": "TEXT", 39 | "notNull": true 40 | }, 41 | { 42 | "fieldPath": "iconUrl", 43 | "columnName": "iconUrl", 44 | "affinity": "TEXT", 45 | "notNull": true 46 | }, 47 | { 48 | "fieldPath": "icon", 49 | "columnName": "icon", 50 | "affinity": "TEXT", 51 | "notNull": true 52 | }, 53 | { 54 | "fieldPath": "temp_low", 55 | "columnName": "temp_low", 56 | "affinity": "TEXT", 57 | "notNull": true 58 | }, 59 | { 60 | "fieldPath": "temp_high", 61 | "columnName": "temp_high", 62 | "affinity": "TEXT", 63 | "notNull": true 64 | }, 65 | { 66 | "fieldPath": "wind_kph", 67 | "columnName": "wind_kph", 68 | "affinity": "INTEGER", 69 | "notNull": true 70 | }, 71 | { 72 | "fieldPath": "wind_dir", 73 | "columnName": "wind_dir", 74 | "affinity": "TEXT", 75 | "notNull": true 76 | }, 77 | { 78 | "fieldPath": "humidity", 79 | "columnName": "humidity", 80 | "affinity": "INTEGER", 81 | "notNull": true 82 | }, 83 | { 84 | "fieldPath": "date", 85 | "columnName": "date", 86 | "affinity": "INTEGER", 87 | "notNull": true 88 | } 89 | ], 90 | "primaryKey": { 91 | "columnNames": [ 92 | "id" 93 | ], 94 | "autoGenerate": false 95 | }, 96 | "indices": [], 97 | "foreignKeys": [] 98 | } 99 | ], 100 | "setupQueries": [ 101 | "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", 102 | "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, \"4bf9c0b54687f2551fead413ed964d04\")" 103 | ] 104 | } 105 | } -------------------------------------------------------------------------------- /weatherapp/app/src/androidTest/java/fr/ekito/myweatherapp/WeatherDAOTest.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp 2 | 3 | import android.support.test.runner.AndroidJUnit4 4 | import fr.ekito.myweatherapp.data.datasource.room.WeatherDAO 5 | import fr.ekito.myweatherapp.data.datasource.room.WeatherDatabase 6 | import fr.ekito.myweatherapp.data.datasource.room.WeatherEntity 7 | import fr.ekito.myweatherapp.data.datasource.webservice.WeatherWebDatasource 8 | import fr.ekito.myweatherapp.data.datasource.webservice.json.geocode.getLocation 9 | import fr.ekito.myweatherapp.data.datasource.webservice.json.weather.getDailyForecasts 10 | import junit.framework.Assert 11 | import kotlinx.coroutines.experimental.runBlocking 12 | import org.junit.After 13 | import org.junit.Before 14 | import org.junit.Test 15 | import org.junit.runner.RunWith 16 | import org.koin.standalone.StandAloneContext.closeKoin 17 | import org.koin.standalone.StandAloneContext.loadKoinModules 18 | import org.koin.standalone.inject 19 | import org.koin.test.KoinTest 20 | import java.util.* 21 | 22 | /** 23 | * WeatherDAOTest is a KoinTest with AndroidJUnit4 runner 24 | * 25 | * KoinTest help inject Koin components from actual runtime 26 | */ 27 | @RunWith(AndroidJUnit4::class) 28 | class WeatherDAOTest : KoinTest { 29 | 30 | /* 31 | * Inject needed components from Koin 32 | */ 33 | val weatherDatabase: WeatherDatabase by inject() 34 | val weatherWebDatasource: WeatherWebDatasource by inject() 35 | val weatherDAO: WeatherDAO by inject() 36 | 37 | 38 | @Before() 39 | fun before() { 40 | // Replace default WeatherDatabase definition with in-memory definition 41 | loadKoinModules(roomTestModule) 42 | } 43 | 44 | @After 45 | fun after() { 46 | weatherDatabase.close() 47 | closeKoin() 48 | } 49 | 50 | @Test 51 | fun testSave() { 52 | val location = "Paris" 53 | 54 | val now = Date() 55 | val entities = getWeatherAsEntities(location, now) 56 | 57 | weatherDAO.saveAll(entities) 58 | val ids = entities.map { it.id } 59 | 60 | val requestedEntities = ids.map { weatherDAO.findWeatherById(it) } 61 | 62 | Assert.assertEquals(entities, requestedEntities) 63 | } 64 | 65 | @Test 66 | fun testFindAllBy() { 67 | val locationParis = "Paris" 68 | val dateParis = Date() 69 | val weatherParis = getWeatherAsEntities(locationParis, dateParis) 70 | weatherDAO.saveAll(weatherParis) 71 | 72 | val locationTlse = "Toulouse" 73 | val dateToulouse = Date() 74 | val weatherToulouse = getWeatherAsEntities(locationTlse, dateToulouse) 75 | weatherDAO.saveAll(weatherToulouse) 76 | 77 | val resultList = weatherDAO.findAllBy(locationTlse, dateToulouse) 78 | 79 | Assert.assertEquals(weatherToulouse, resultList) 80 | } 81 | 82 | @Test 83 | fun testFindLatest() { 84 | val locationParis = "Paris" 85 | val dateParis = Date() 86 | val weatherParis = getWeatherAsEntities(locationParis, dateParis) 87 | weatherDAO.saveAll(weatherParis) 88 | 89 | val locationBerlin = "Berlin" 90 | val dateBerlin = Date() 91 | val weatherBerlin = getWeatherAsEntities(locationBerlin, dateBerlin) 92 | weatherDAO.saveAll(weatherBerlin) 93 | 94 | val locationTlse = "Toulouse" 95 | val dateToulouse = Date() 96 | val weatherToulouse = getWeatherAsEntities(locationTlse, dateToulouse) 97 | weatherDAO.saveAll(weatherToulouse) 98 | 99 | val result: WeatherEntity = weatherDAO.findLatestWeather().first() 100 | val resultList = weatherDAO.findAllBy(result.location, result.date) 101 | 102 | Assert.assertEquals(weatherToulouse, resultList) 103 | } 104 | 105 | private fun getWeatherAsEntities( 106 | locationParis: String, 107 | dateParis: Date 108 | ): List { 109 | return runBlocking { 110 | val l = weatherWebDatasource.geocode(locationParis).await().getLocation() ?: error("") 111 | weatherWebDatasource.weather(l.lat, l.lng, "EN").await() 112 | .getDailyForecasts(locationParis).map { WeatherEntity.from(it, dateParis) } 113 | } 114 | } 115 | } -------------------------------------------------------------------------------- /weatherapp/app/src/androidTest/java/fr/ekito/myweatherapp/WeatherRepositoryTest.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp 2 | 3 | import android.support.test.runner.AndroidJUnit4 4 | import fr.ekito.myweatherapp.data.repository.WeatherRepository 5 | import junit.framework.Assert 6 | import kotlinx.coroutines.experimental.runBlocking 7 | import org.junit.After 8 | import org.junit.Before 9 | import org.junit.Test 10 | import org.junit.runner.RunWith 11 | import org.koin.standalone.StandAloneContext.closeKoin 12 | import org.koin.standalone.StandAloneContext.loadKoinModules 13 | import org.koin.standalone.inject 14 | import org.koin.test.KoinTest 15 | 16 | /** 17 | * WeatherRepositoryTest is a KoinTest with AndroidJUnit4 runner 18 | * 19 | * KoinTest help inject Koin components from actual runtime 20 | */ 21 | @RunWith(AndroidJUnit4::class) 22 | class WeatherRepositoryTest : KoinTest { 23 | 24 | /* 25 | * Inject WeatherRepository from Koin 26 | */ 27 | val weatherRepository: WeatherRepository by inject() 28 | 29 | @Before() 30 | fun before() { 31 | loadKoinModules(roomTestModule) 32 | } 33 | 34 | @After 35 | fun after() { 36 | closeKoin() 37 | } 38 | 39 | @Test 40 | fun testGetDefault() = runBlocking { 41 | val defaultWeather = weatherRepository.getWeather().await() 42 | val defaultWeather2 = weatherRepository.getWeather().await() 43 | Assert.assertEquals(defaultWeather, defaultWeather2) 44 | } 45 | 46 | @Test 47 | fun testGetWeatherDetail() = runBlocking { 48 | val defaultWeather = weatherRepository.getWeather().await() 49 | 50 | val result = defaultWeather.first() 51 | val first = weatherRepository.getWeatherDetail(result.id).await() 52 | Assert.assertEquals(result, first) 53 | } 54 | 55 | @Test 56 | fun testGetLatest() = runBlocking { 57 | weatherRepository.getWeather().await() 58 | weatherRepository.getWeather("London").await() 59 | val toulouse = weatherRepository.getWeather("Toulouse").await() 60 | val defaultWeather3 = weatherRepository.getWeather().await() 61 | Assert.assertEquals(defaultWeather3, toulouse) 62 | } 63 | } -------------------------------------------------------------------------------- /weatherapp/app/src/androidTest/java/fr/ekito/myweatherapp/room_test_modules.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp 2 | 3 | import android.arch.persistence.room.Room 4 | import fr.ekito.myweatherapp.data.datasource.room.WeatherDatabase 5 | import org.koin.dsl.module.applicationContext 6 | 7 | /** 8 | * In-Memory Room Database definition 9 | */ 10 | val roomTestModule = applicationContext { 11 | bean { 12 | Room.inMemoryDatabaseBuilder(get(), WeatherDatabase::class.java) 13 | .allowMainThreadQueries() 14 | .build() 15 | } 16 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/assets/json/geocode_berlin.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": "OK", 3 | "results": [ 4 | { 5 | "address_components": [ 6 | { 7 | "lang_name": null, 8 | "short_name": "Berlin", 9 | "types": [ 10 | "locality", 11 | "political" 12 | ] 13 | }, 14 | { 15 | "lang_name": null, 16 | "short_name": "Berlin", 17 | "types": [ 18 | "administrative_area_level_1", 19 | "political" 20 | ] 21 | }, 22 | { 23 | "lang_name": null, 24 | "short_name": "DE", 25 | "types": [ 26 | "country", 27 | "political" 28 | ] 29 | } 30 | ], 31 | "formatted_address": "Berlin, Germany", 32 | "geometry": { 33 | "location": { 34 | "lat": 52.52000659999999, 35 | "lng": 13.404954 36 | }, 37 | "location_type": "APPROXIMATE", 38 | "viewport": { 39 | "northeast": { 40 | "lat": 52.6754542, 41 | "lng": 13.7611175 42 | }, 43 | "southwest": { 44 | "lat": 52.33962959999999, 45 | "lng": 13.0911733 46 | } 47 | } 48 | }, 49 | "place_id": "ChIJAVkDPzdOqEcRcDteW0YgIQQ", 50 | "types": [ 51 | "locality", 52 | "political" 53 | ] 54 | } 55 | ] 56 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/assets/json/geocode_london.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": "OK", 3 | "results": [ 4 | { 5 | "address_components": [ 6 | { 7 | "lang_name": null, 8 | "short_name": "London", 9 | "types": [ 10 | "locality", 11 | "political" 12 | ] 13 | }, 14 | { 15 | "lang_name": null, 16 | "short_name": "London", 17 | "types": [ 18 | "postal_town" 19 | ] 20 | }, 21 | { 22 | "lang_name": null, 23 | "short_name": "Greater London", 24 | "types": [ 25 | "administrative_area_level_2", 26 | "political" 27 | ] 28 | }, 29 | { 30 | "lang_name": null, 31 | "short_name": "England", 32 | "types": [ 33 | "administrative_area_level_1", 34 | "political" 35 | ] 36 | }, 37 | { 38 | "lang_name": null, 39 | "short_name": "GB", 40 | "types": [ 41 | "country", 42 | "political" 43 | ] 44 | } 45 | ], 46 | "formatted_address": "London, UK", 47 | "geometry": { 48 | "location": { 49 | "lat": 51.5073509, 50 | "lng": -0.1277583 51 | }, 52 | "location_type": "APPROXIMATE", 53 | "viewport": { 54 | "northeast": { 55 | "lat": 51.6723432, 56 | "lng": 0.148271 57 | }, 58 | "southwest": { 59 | "lat": 51.38494009999999, 60 | "lng": -0.3514683 61 | } 62 | } 63 | }, 64 | "place_id": "ChIJdd4hrwug2EcRmSrV3Vo6llI", 65 | "types": [ 66 | "locality", 67 | "political" 68 | ] 69 | } 70 | ] 71 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/assets/json/geocode_madrid.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": "OK", 3 | "results": [ 4 | { 5 | "address_components": [ 6 | { 7 | "lang_name": null, 8 | "short_name": "Madrid", 9 | "types": [ 10 | "locality", 11 | "political" 12 | ] 13 | }, 14 | { 15 | "lang_name": null, 16 | "short_name": "M", 17 | "types": [ 18 | "administrative_area_level_2", 19 | "political" 20 | ] 21 | }, 22 | { 23 | "lang_name": null, 24 | "short_name": "Community of Madrid", 25 | "types": [ 26 | "administrative_area_level_1", 27 | "political" 28 | ] 29 | }, 30 | { 31 | "lang_name": null, 32 | "short_name": "ES", 33 | "types": [ 34 | "country", 35 | "political" 36 | ] 37 | } 38 | ], 39 | "formatted_address": "Madrid, Spain", 40 | "geometry": { 41 | "location": { 42 | "lat": 40.4167754, 43 | "lng": -3.7037902 44 | }, 45 | "location_type": "APPROXIMATE", 46 | "viewport": { 47 | "northeast": { 48 | "lat": 40.5638447, 49 | "lng": -3.5249115 50 | }, 51 | "southwest": { 52 | "lat": 40.3120639, 53 | "lng": -3.8341618 54 | } 55 | } 56 | }, 57 | "place_id": "ChIJgTwKgJcpQg0RaSKMYcHeNsQ", 58 | "types": [ 59 | "locality", 60 | "political" 61 | ] 62 | } 63 | ] 64 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/assets/json/geocode_paris.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": "OK", 3 | "results": [ 4 | { 5 | "address_components": [ 6 | { 7 | "lang_name": null, 8 | "short_name": "Paris", 9 | "types": [ 10 | "locality", 11 | "political" 12 | ] 13 | }, 14 | { 15 | "lang_name": null, 16 | "short_name": "Paris", 17 | "types": [ 18 | "administrative_area_level_2", 19 | "political" 20 | ] 21 | }, 22 | { 23 | "lang_name": null, 24 | "short_name": "Île-de-France", 25 | "types": [ 26 | "administrative_area_level_1", 27 | "political" 28 | ] 29 | }, 30 | { 31 | "lang_name": null, 32 | "short_name": "FR", 33 | "types": [ 34 | "country", 35 | "political" 36 | ] 37 | } 38 | ], 39 | "formatted_address": "Paris, France", 40 | "geometry": { 41 | "location": { 42 | "lat": 48.856614, 43 | "lng": 2.3522219 44 | }, 45 | "location_type": "APPROXIMATE", 46 | "viewport": { 47 | "northeast": { 48 | "lat": 48.9021449, 49 | "lng": 2.4699208 50 | }, 51 | "southwest": { 52 | "lat": 48.815573, 53 | "lng": 2.225193 54 | } 55 | } 56 | }, 57 | "place_id": "ChIJD7fiBh9u5kcRYJSMaMOCCwQ", 58 | "types": [ 59 | "locality", 60 | "political" 61 | ] 62 | } 63 | ] 64 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/assets/json/geocode_toulouse.json: -------------------------------------------------------------------------------- 1 | { 2 | "status": "OK", 3 | "results": [ 4 | { 5 | "address_components": [ 6 | { 7 | "lang_name": null, 8 | "short_name": "Toulouse", 9 | "types": [ 10 | "locality", 11 | "political" 12 | ] 13 | }, 14 | { 15 | "lang_name": null, 16 | "short_name": "Haute-Garonne", 17 | "types": [ 18 | "administrative_area_level_2", 19 | "political" 20 | ] 21 | }, 22 | { 23 | "lang_name": null, 24 | "short_name": "Occitanie", 25 | "types": [ 26 | "administrative_area_level_1", 27 | "political" 28 | ] 29 | }, 30 | { 31 | "lang_name": null, 32 | "short_name": "FR", 33 | "types": [ 34 | "country", 35 | "political" 36 | ] 37 | } 38 | ], 39 | "formatted_address": "Toulouse, France", 40 | "geometry": { 41 | "location": { 42 | "lat": 43.604652, 43 | "lng": 1.444209 44 | }, 45 | "location_type": "APPROXIMATE", 46 | "viewport": { 47 | "northeast": { 48 | "lat": 43.6686919, 49 | "lng": 1.515354 50 | }, 51 | "southwest": { 52 | "lat": 43.532708, 53 | "lng": 1.350328 54 | } 55 | } 56 | }, 57 | "place_id": "ChIJ_1J17G-7rhIRMBBBL5z2BgQ", 58 | "types": [ 59 | "locality", 60 | "political" 61 | ] 62 | } 63 | ] 64 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/assets/json/weather_madrid.json: -------------------------------------------------------------------------------- 1 | { 2 | "response": { 3 | "version": "0.1", 4 | "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", 5 | "features": { 6 | "forecast": 1 7 | } 8 | }, 9 | "forecast": { 10 | "txtForecast": { 11 | "date": "4:04 PM CET", 12 | "forecastday": [ 13 | { 14 | "period": 0, 15 | "icon": "clear", 16 | "iconUrl": "http://icons.wxug.com/i/c/k/clear.gif", 17 | "title": "Friday", 18 | "fcttext": "Mostly clear. Lows overnight in the low 30s.", 19 | "fcttextMetric": "Mostly clear. Low 1C.", 20 | "pop": "10" 21 | }, 22 | { 23 | "period": 1, 24 | "icon": "nt_clear", 25 | "iconUrl": "http://icons.wxug.com/i/c/k/nt_clear.gif", 26 | "title": "Friday Night", 27 | "fcttext": "Mostly clear. Low 33F. Winds light and variable.", 28 | "fcttextMetric": "Mainly clear skies. Low 1C. Winds light and variable.", 29 | "pop": "10" 30 | }, 31 | { 32 | "period": 2, 33 | "icon": "clear", 34 | "iconUrl": "http://icons.wxug.com/i/c/k/clear.gif", 35 | "title": "Saturday", 36 | "fcttext": "Mostly sunny skies. High 58F. Winds light and variable.", 37 | "fcttextMetric": "Mostly sunny skies. High around 15C. Winds light and variable.", 38 | "pop": "10" 39 | }, 40 | { 41 | "period": 3, 42 | "icon": "nt_partlycloudy", 43 | "iconUrl": "http://icons.wxug.com/i/c/k/nt_partlycloudy.gif", 44 | "title": "Saturday Night", 45 | "fcttext": "Mostly cloudy skies early will become partly cloudy late. Low around 40F. Winds N at 5 to 10 mph.", 46 | "fcttextMetric": "Mostly cloudy skies early will become partly cloudy late. Low around 5C. Winds N at 10 to 15 km/h.", 47 | "pop": "10" 48 | }, 49 | { 50 | "period": 4, 51 | "icon": "partlycloudy", 52 | "iconUrl": "http://icons.wxug.com/i/c/k/partlycloudy.gif", 53 | "title": "Sunday", 54 | "fcttext": "Sunshine and clouds mixed. High 58F. Winds NE at 10 to 15 mph.", 55 | "fcttextMetric": "Sunshine and clouds mixed. High around 15C. Winds NE at 15 to 25 km/h.", 56 | "pop": "10" 57 | }, 58 | { 59 | "period": 5, 60 | "icon": "nt_clear", 61 | "iconUrl": "http://icons.wxug.com/i/c/k/nt_clear.gif", 62 | "title": "Sunday Night", 63 | "fcttext": "Clear skies. Low 36F. Winds NNE at 5 to 10 mph.", 64 | "fcttextMetric": "Clear skies. Low 3C. Winds NNE at 10 to 15 km/h.", 65 | "pop": "10" 66 | }, 67 | { 68 | "period": 6, 69 | "icon": "clear", 70 | "iconUrl": "http://icons.wxug.com/i/c/k/clear.gif", 71 | "title": "Monday", 72 | "fcttext": "Sunny skies. High 58F. Winds NE at 10 to 15 mph.", 73 | "fcttextMetric": "A mainly sunny sky. High near 15C. Winds NE at 10 to 15 km/h.", 74 | "pop": "10" 75 | }, 76 | { 77 | "period": 7, 78 | "icon": "nt_clear", 79 | "iconUrl": "http://icons.wxug.com/i/c/k/nt_clear.gif", 80 | "title": "Monday Night", 81 | "fcttext": "Clear skies. Low 36F. Winds NE at 5 to 10 mph.", 82 | "fcttextMetric": "Clear skies. Low 2C. Winds NE at 10 to 15 km/h.", 83 | "pop": "10" 84 | } 85 | ] 86 | }, 87 | "simpleforecast": { 88 | "forecastday": [ 89 | { 90 | "date": { 91 | "epoch": "1487354400", 92 | "pretty": "7:00 PM CET on February 17, 2017", 93 | "day": 17, 94 | "month": 2, 95 | "year": 2017, 96 | "yday": 47, 97 | "hour": 19, 98 | "min": "00", 99 | "sec": 0, 100 | "isdst": "0", 101 | "monthname": "February", 102 | "monthnameShort": "Feb", 103 | "weekdayShort": "Fri", 104 | "weekday": "Friday", 105 | "ampm": "PM", 106 | "tzShort": "CET", 107 | "tzLong": "Europe/Madrid" 108 | }, 109 | "period": 1, 110 | "high": { 111 | "fahrenheit": "59", 112 | "celsius": "15" 113 | }, 114 | "low": { 115 | "fahrenheit": "33", 116 | "celsius": "1" 117 | }, 118 | "conditions": "Clear", 119 | "icon": "clear", 120 | "iconUrl": "http://icons.wxug.com/i/c/k/clear.gif", 121 | "skyicon": "", 122 | "pop": 10, 123 | "qpfAllday": { 124 | "in": 0.0, 125 | "mm": 0 126 | }, 127 | "qpfDay": { 128 | "in": null, 129 | "mm": null 130 | }, 131 | "qpfNight": { 132 | "in": 0.0, 133 | "mm": 0 134 | }, 135 | "snowAllday": { 136 | "in": 0.0, 137 | "cm": 0.0 138 | }, 139 | "snowDay": { 140 | "in": null, 141 | "cm": null 142 | }, 143 | "snowNight": { 144 | "in": 0.0, 145 | "cm": 0.0 146 | }, 147 | "maxwind": { 148 | "mph": 2, 149 | "kph": 4, 150 | "dir": "North", 151 | "degrees": 0 152 | }, 153 | "avewind": { 154 | "mph": 0, 155 | "kph": 0, 156 | "dir": "Variable", 157 | "degrees": 0 158 | }, 159 | "avehumidity": 75, 160 | "maxhumidity": 0, 161 | "minhumidity": 0 162 | }, 163 | { 164 | "date": { 165 | "epoch": "1487440800", 166 | "pretty": "7:00 PM CET on February 18, 2017", 167 | "day": 18, 168 | "month": 2, 169 | "year": 2017, 170 | "yday": 48, 171 | "hour": 19, 172 | "min": "00", 173 | "sec": 0, 174 | "isdst": "0", 175 | "monthname": "February", 176 | "monthnameShort": "Feb", 177 | "weekdayShort": "Sat", 178 | "weekday": "Saturday", 179 | "ampm": "PM", 180 | "tzShort": "CET", 181 | "tzLong": "Europe/Madrid" 182 | }, 183 | "period": 2, 184 | "high": { 185 | "fahrenheit": "58", 186 | "celsius": "14" 187 | }, 188 | "low": { 189 | "fahrenheit": "40", 190 | "celsius": "4" 191 | }, 192 | "conditions": "Clear", 193 | "icon": "clear", 194 | "iconUrl": "http://icons.wxug.com/i/c/k/clear.gif", 195 | "skyicon": "", 196 | "pop": 10, 197 | "qpfAllday": { 198 | "in": 0.0, 199 | "mm": 0 200 | }, 201 | "qpfDay": { 202 | "in": 0.0, 203 | "mm": 0 204 | }, 205 | "qpfNight": { 206 | "in": 0.0, 207 | "mm": 0 208 | }, 209 | "snowAllday": { 210 | "in": 0.0, 211 | "cm": 0.0 212 | }, 213 | "snowDay": { 214 | "in": 0.0, 215 | "cm": 0.0 216 | }, 217 | "snowNight": { 218 | "in": 0.0, 219 | "cm": 0.0 220 | }, 221 | "maxwind": { 222 | "mph": 5, 223 | "kph": 8, 224 | "dir": "W", 225 | "degrees": 268 226 | }, 227 | "avewind": { 228 | "mph": 4, 229 | "kph": 6, 230 | "dir": "W", 231 | "degrees": 268 232 | }, 233 | "avehumidity": 65, 234 | "maxhumidity": 0, 235 | "minhumidity": 0 236 | }, 237 | { 238 | "date": { 239 | "epoch": "1487527200", 240 | "pretty": "7:00 PM CET on February 19, 2017", 241 | "day": 19, 242 | "month": 2, 243 | "year": 2017, 244 | "yday": 49, 245 | "hour": 19, 246 | "min": "00", 247 | "sec": 0, 248 | "isdst": "0", 249 | "monthname": "February", 250 | "monthnameShort": "Feb", 251 | "weekdayShort": "Sun", 252 | "weekday": "Sunday", 253 | "ampm": "PM", 254 | "tzShort": "CET", 255 | "tzLong": "Europe/Madrid" 256 | }, 257 | "period": 3, 258 | "high": { 259 | "fahrenheit": "58", 260 | "celsius": "14" 261 | }, 262 | "low": { 263 | "fahrenheit": "36", 264 | "celsius": "2" 265 | }, 266 | "conditions": "Partly Cloudy", 267 | "icon": "partlycloudy", 268 | "iconUrl": "http://icons.wxug.com/i/c/k/partlycloudy.gif", 269 | "skyicon": "", 270 | "pop": 10, 271 | "qpfAllday": { 272 | "in": 0.0, 273 | "mm": 0 274 | }, 275 | "qpfDay": { 276 | "in": 0.0, 277 | "mm": 0 278 | }, 279 | "qpfNight": { 280 | "in": 0.0, 281 | "mm": 0 282 | }, 283 | "snowAllday": { 284 | "in": 0.0, 285 | "cm": 0.0 286 | }, 287 | "snowDay": { 288 | "in": 0.0, 289 | "cm": 0.0 290 | }, 291 | "snowNight": { 292 | "in": 0.0, 293 | "cm": 0.0 294 | }, 295 | "maxwind": { 296 | "mph": 15, 297 | "kph": 24, 298 | "dir": "NE", 299 | "degrees": 48 300 | }, 301 | "avewind": { 302 | "mph": 10, 303 | "kph": 16, 304 | "dir": "NE", 305 | "degrees": 48 306 | }, 307 | "avehumidity": 64, 308 | "maxhumidity": 0, 309 | "minhumidity": 0 310 | }, 311 | { 312 | "date": { 313 | "epoch": "1487613600", 314 | "pretty": "7:00 PM CET on February 20, 2017", 315 | "day": 20, 316 | "month": 2, 317 | "year": 2017, 318 | "yday": 50, 319 | "hour": 19, 320 | "min": "00", 321 | "sec": 0, 322 | "isdst": "0", 323 | "monthname": "February", 324 | "monthnameShort": "Feb", 325 | "weekdayShort": "Mon", 326 | "weekday": "Monday", 327 | "ampm": "PM", 328 | "tzShort": "CET", 329 | "tzLong": "Europe/Madrid" 330 | }, 331 | "period": 4, 332 | "high": { 333 | "fahrenheit": "58", 334 | "celsius": "14" 335 | }, 336 | "low": { 337 | "fahrenheit": "36", 338 | "celsius": "2" 339 | }, 340 | "conditions": "Clear", 341 | "icon": "clear", 342 | "iconUrl": "http://icons.wxug.com/i/c/k/clear.gif", 343 | "skyicon": "", 344 | "pop": 10, 345 | "qpfAllday": { 346 | "in": 0.0, 347 | "mm": 0 348 | }, 349 | "qpfDay": { 350 | "in": 0.0, 351 | "mm": 0 352 | }, 353 | "qpfNight": { 354 | "in": 0.0, 355 | "mm": 0 356 | }, 357 | "snowAllday": { 358 | "in": 0.0, 359 | "cm": 0.0 360 | }, 361 | "snowDay": { 362 | "in": 0.0, 363 | "cm": 0.0 364 | }, 365 | "snowNight": { 366 | "in": 0.0, 367 | "cm": 0.0 368 | }, 369 | "maxwind": { 370 | "mph": 15, 371 | "kph": 24, 372 | "dir": "NE", 373 | "degrees": 51 374 | }, 375 | "avewind": { 376 | "mph": 10, 377 | "kph": 16, 378 | "dir": "NE", 379 | "degrees": 51 380 | }, 381 | "avehumidity": 62, 382 | "maxhumidity": 0, 383 | "minhumidity": 0 384 | } 385 | ] 386 | } 387 | } 388 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/assets/koin.properties: -------------------------------------------------------------------------------- 1 | SERVER_URL=https://my-weather-api.herokuapp.com/ -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/MainApplication.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp 2 | 3 | import android.app.Application 4 | import com.joanzapata.iconify.Iconify 5 | import com.joanzapata.iconify.fonts.WeathericonsModule 6 | import fr.ekito.myweatherapp.di.offlineWeatherApp 7 | import org.koin.android.ext.android.startKoin 8 | 9 | /** 10 | * Main Application 11 | */ 12 | class MainApplication : Application() { 13 | 14 | override fun onCreate() { 15 | super.onCreate() 16 | 17 | // start Koin context 18 | startKoin(this, offlineWeatherApp) 19 | 20 | Iconify 21 | .with(WeathericonsModule()) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/room/Converters.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.room 2 | 3 | import android.arch.persistence.room.TypeConverter 4 | import java.util.* 5 | 6 | /** 7 | * Help Convert Data types for Room 8 | */ 9 | class Converters { 10 | @TypeConverter 11 | fun fromTimestamp(value: Long?): Date? { 12 | return if (value == null) null else Date(value) 13 | } 14 | 15 | @TypeConverter 16 | fun dateToTimestamp(date: Date?): Long? { 17 | return date?.time 18 | } 19 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/room/WeatherDAO.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.room 2 | 3 | import android.arch.persistence.room.Dao 4 | import android.arch.persistence.room.Insert 5 | import android.arch.persistence.room.Query 6 | import java.util.* 7 | 8 | @Dao 9 | interface WeatherDAO { 10 | 11 | /** 12 | * Save entities 13 | */ 14 | @Insert 15 | fun saveAll(entities: List) 16 | 17 | /** 18 | * Find any WeatherEntity by location and date 19 | * @return List 20 | */ 21 | @Query("SELECT * FROM weather WHERE location = :location AND date = :date") 22 | fun findAllBy(location: String, date: Date): List 23 | 24 | /** 25 | * Find Latest WeatherEntity by Date 26 | * @return List 27 | */ 28 | @Query("SELECT * FROM weather GROUP BY date ORDER BY date DESC LIMIT 1") 29 | fun findLatestWeather(): List 30 | 31 | /** 32 | * Find WeatherEntity for given id 33 | * @return WeatherEntity 34 | */ 35 | @Query("SELECT * FROM weather WHERE id = :id") 36 | fun findWeatherById(id: String): WeatherEntity 37 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/room/WeatherDatabase.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.room 2 | 3 | import android.arch.persistence.room.Database 4 | import android.arch.persistence.room.RoomDatabase 5 | import android.arch.persistence.room.TypeConverters 6 | 7 | @Database(entities = [WeatherEntity::class], version = 1) 8 | @TypeConverters(Converters::class) 9 | abstract class WeatherDatabase : RoomDatabase() { 10 | 11 | abstract fun weatherDAO(): WeatherDAO 12 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/room/WeatherEntity.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.room 2 | 3 | import android.arch.persistence.room.Entity 4 | import android.arch.persistence.room.PrimaryKey 5 | import fr.ekito.myweatherapp.domain.DailyForecastModel 6 | import java.util.* 7 | 8 | @Entity(tableName = "weather") 9 | data class WeatherEntity( 10 | @PrimaryKey 11 | val id: String, 12 | val location: String, 13 | val day: String, 14 | val shortText: String, 15 | val fullText: String, 16 | val iconUrl: String, 17 | val icon: String, 18 | val temp_low: String, 19 | val temp_high: String, 20 | val wind_kph: Int, 21 | val wind_dir: String, 22 | val humidity: Int, 23 | val date: Date 24 | ) { 25 | companion object { 26 | fun from(model: DailyForecastModel, date: Date) = WeatherEntity( 27 | model.id, 28 | model.location, 29 | model.day, 30 | model.shortText, 31 | model.fullText, 32 | model.iconUrl, 33 | model.icon, 34 | model.temperature.low, 35 | model.temperature.high, 36 | model.wind.kph, 37 | model.wind.dir, 38 | model.humidity.humidity, 39 | date 40 | ) 41 | } 42 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/WeatherWebDatasource.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice 2 | 3 | import io.reactivex.Single 4 | import fr.ekito.myweatherapp.data.datasource.webservice.json.geocode.Geocode 5 | import fr.ekito.myweatherapp.data.datasource.webservice.json.weather.Weather 6 | import kotlinx.coroutines.experimental.Deferred 7 | import retrofit2.http.GET 8 | import retrofit2.http.Headers 9 | import retrofit2.http.Query 10 | 11 | /** 12 | * Weather datasource - Retrofit tagged 13 | */ 14 | interface WeatherWebDatasource { 15 | 16 | @GET("/geocode") 17 | @Headers("Content-type: application/json") 18 | fun geocode(@Query("location") address: String): Deferred 19 | 20 | @GET("/weather") 21 | @Headers("Content-type: application/json") 22 | fun weather(@Query("lat") lat: Double?, @Query("lon") lon: Double?, @Query("lang") lang: String): Deferred 23 | 24 | } 25 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/AddressComponent.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class AddressComponent( 7 | @SerializedName("long_name") @Expose var longName: String? = null, 8 | @SerializedName("short_name") @Expose var shortName: String? = null, 9 | @SerializedName("types") @Expose var types: List = emptyList() 10 | ) 11 | 12 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/Geocode.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Geocode( 7 | @SerializedName("results") @Expose var results: List = emptyList(), 8 | @SerializedName("status") @Expose var status: String? = null 9 | ) 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/GeocodeExt.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | /** 4 | * Extract Location from Geocode 5 | */ 6 | fun Geocode.getLocation(): Location? = results.firstOrNull()?.geometry?.location -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/Geometry.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Geometry( 7 | @SerializedName("location") @Expose var location: Location? = null, 8 | @SerializedName("location_type") @Expose var locationType: String? = null, 9 | @SerializedName("viewport") @Expose var viewport: Viewport? = null 10 | ) 11 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/Location.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Location( 7 | @SerializedName("lat") @Expose var lat: Double? = null, 8 | @SerializedName("lng") @Expose var lng: Double? = null 9 | ) -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/Northeast.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Northeast( 7 | @SerializedName("lat") @Expose var lat: Double? = null, 8 | @SerializedName("lng") @Expose var lng: Double? = null 9 | ) 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/Result.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | import java.util.* 6 | 7 | data class Result( 8 | @SerializedName("address_components") @Expose 9 | var addressComponents: List = emptyList(), 10 | @SerializedName("formatted_address") @Expose var formattedAddress: String? = null, 11 | @SerializedName("geometry") @Expose var geometry: Geometry? = null, 12 | @SerializedName("place_id") @Expose var placeId: String? = null, 13 | @SerializedName("types") @Expose var types: List = ArrayList() 14 | ) 15 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/Southwest.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Southwest( 7 | @SerializedName("lat") @Expose var lat: Double? = null, 8 | @SerializedName("lng") @Expose var lng: Double? = null 9 | ) 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/geocode/Viewport.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.geocode 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Viewport( 7 | @SerializedName("northeast") @Expose var northeast: Northeast? = null, 8 | @SerializedName("southwest") @Expose var southwest: Southwest? = null 9 | ) -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Avewind.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class Avewind( 6 | @Expose var mph: Int? = null, 7 | @Expose var kph: Int? = null, 8 | @Expose var dir: String? = null, 9 | @Expose var degrees: Int? = null 10 | ) 11 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Date.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Date( 7 | @Expose var epoch: String? = null, 8 | @Expose var pretty: String? = null, 9 | @Expose var day: Int? = null, 10 | @Expose var month: Int? = null, 11 | @Expose var year: Int? = null, 12 | @Expose var yday: Int? = null, 13 | @Expose var hour: Int? = null, 14 | @Expose var min: String? = null, 15 | @Expose var sec: Int? = null, 16 | @Expose var isdst: String? = null, 17 | @Expose var monthname: String? = null, 18 | @SerializedName("monthname_short") 19 | @Expose var monthnameShort: String? = null, 20 | @SerializedName("weekday_short") 21 | @Expose var weekdayShort: String? = null, 22 | @Expose var weekday: String? = null, 23 | @Expose var ampm: String? = null, 24 | @SerializedName("tz_short") 25 | @Expose var tzShort: String? = null, 26 | @SerializedName("tz_long") 27 | @Expose var tzLong: String? = null 28 | ) 29 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Features.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class Features(@Expose var forecast: Int? = null) -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Forecast.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Forecast( 7 | @SerializedName("txtForecast") @Expose var txtForecast: TxtForecast? = null, 8 | @SerializedName("simpleforecast") @Expose var simpleForecast: SimpleForecast? = null 9 | ) 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Forecastday.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class ForecastDay( 7 | @Expose var period: Int? = null, 8 | @Expose var icon: String? = null, 9 | @SerializedName("iconUrl") 10 | @Expose var iconUrl: String? = null, 11 | @Expose var title: String? = null, 12 | @Expose var fcttext: String? = null, 13 | @SerializedName("fcttextMetric") 14 | @Expose var fcttextMetric: String? = null, 15 | @Expose var pop: String? = null 16 | ) 17 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Forecastday_.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class Forecastday_( 7 | @Expose var date: Date? = null, 8 | @Expose var period: Int? = null, 9 | @Expose var high: High? = null, 10 | @Expose var low: Low? = null, 11 | @Expose var conditions: String? = null, 12 | @Expose var icon: String? = null, 13 | @SerializedName("iconUrl") @Expose var iconUrl: String? = null, 14 | @Expose var skyicon: String? = null, 15 | @Expose var pop: Int? = null, 16 | @SerializedName("qpf_allday") @Expose var qpfAllday: QpfAllday? = null, 17 | @SerializedName("qpf_day") @Expose var qpfDay: QpfDay? = null, 18 | @SerializedName("qpf_night") @Expose var qpfNight: QpfNight? = null, 19 | @SerializedName("snow_allday") @Expose var snowAllday: SnowAllday? = null, 20 | @SerializedName("snow_day") @Expose var snowDay: SnowDay? = null, 21 | @SerializedName("snow_night") @Expose var snowNight: SnowNight? = null, 22 | @Expose var maxwind: Maxwind? = null, 23 | @Expose var avewind: Avewind? = null, 24 | @Expose var avehumidity: Int? = null, 25 | @Expose var maxhumidity: Int? = null, 26 | @Expose var minhumidity: Int? = null 27 | ) 28 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/High.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class High( 6 | @Expose var fahrenheit: String? = null, 7 | @Expose var celsius: String? = null 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Low.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class Low( 6 | @Expose var fahrenheit: String? = null, 7 | @Expose var celsius: String? = null 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Maxwind.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class Maxwind( 6 | @Expose var mph: Int? = null, 7 | @Expose var kph: Int? = null, 8 | @Expose var dir: String? = null, 9 | @Expose var degrees: Int? = null 10 | ) 11 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/QpfAllday.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class QpfAllday(@Expose var `in`: Double? = null, @Expose var mm: Int? = null) 6 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/QpfDay.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class QpfDay( 6 | @Expose var `in`: Double? = null, 7 | @Expose var mm: Int? = null 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/QpfNight.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class QpfNight( 6 | @Expose var `in`: Double? = null, 7 | @Expose var mm: Int? = null 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Response.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class Response( 6 | @Expose var version: String? = null, 7 | @Expose var termsofService: String? = null, 8 | @Expose var features: Features? = null 9 | ) 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Simpleforecast.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class SimpleForecast(@Expose var forecastday: List = emptyList()) 6 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/SnowAllday.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class SnowAllday( 6 | @Expose var `in`: Double? = null, 7 | @Expose var cm: Double? = null 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/SnowDay.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class SnowDay( 6 | @Expose var `in`: Double? = null, 7 | @Expose var cm: Double? = null 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/SnowNight.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class SnowNight( 6 | @Expose var `in`: Double? = null, 7 | @Expose var cm: Double? = null 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/TxtForecast.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class TxtForecast( 6 | @Expose var date: String? = null, 7 | @Expose var forecastday: List = emptyList() 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/Weather.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import com.google.gson.annotations.Expose 4 | 5 | data class Weather( 6 | @Expose var response: Response? = null, 7 | @Expose var forecast: Forecast? = null 8 | ) 9 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/json/weather/WeatherExt.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.json.weather 2 | 3 | import fr.ekito.myweatherapp.domain.DailyForecastModel 4 | import fr.ekito.myweatherapp.domain.PREFIX 5 | 6 | /** 7 | * Extract Weather DailyForecastModel list from Weather 8 | */ 9 | fun Weather.getDailyForecasts(location: String): List { 10 | val txtList: List = forecast?.txtForecast?.forecastday.orEmpty() 11 | return forecast?.simpleForecast?.forecastday.orEmpty() 12 | .map { f: Forecastday_ -> DailyForecastModel.from(location, f) } 13 | .map { f -> 14 | f.copy( 15 | fullText = txtList.firstOrNull { it.title ?: "" == f.day }?.fcttext ?: "" 16 | ) 17 | } 18 | .filter { f -> !f.icon.startsWith(PREFIX) } 19 | 20 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/local/AndroidJsonReader.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.local 2 | 3 | import android.app.Application 4 | import fr.ekito.myweatherapp.data.datasource.webservice.local.BaseReader 5 | import java.io.BufferedReader 6 | import java.io.InputStreamReader 7 | 8 | /** 9 | * Read Json File from assets/json 10 | */ 11 | class AndroidJsonReader(val application: Application) : BaseReader() { 12 | 13 | override fun getAllFiles(): List = application.assets.list("json").toList() 14 | 15 | override fun readJsonFile(jsonFile: String): String { 16 | val buf = StringBuilder() 17 | val json = application.assets.open("json/" + jsonFile) 18 | BufferedReader(InputStreamReader(json, "UTF-8")) 19 | .use { 20 | val list = it.lineSequence().toList() 21 | buf.append(list.joinToString("\n")) 22 | } 23 | 24 | return buf.toString() 25 | } 26 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/local/BaseReader.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.local 2 | 3 | import com.google.gson.Gson 4 | import fr.ekito.myweatherapp.data.datasource.webservice.json.geocode.Geocode 5 | import fr.ekito.myweatherapp.data.datasource.webservice.json.geocode.Location 6 | import fr.ekito.myweatherapp.data.datasource.webservice.json.weather.Weather 7 | 8 | /** 9 | * Common parts for Json reader 10 | */ 11 | abstract class BaseReader : JsonReader { 12 | 13 | private val gson = Gson() 14 | private val geocode_prefix = "geocode_" 15 | private val weather_prefix = "weather_" 16 | private val json_file = ".json" 17 | 18 | override fun getAllLocations(): Map { 19 | val list = getAllFiles() 20 | return list.filter { it.startsWith(geocode_prefix) }.map { 21 | val name = it.replace(geocode_prefix, "").replace(".json", "") 22 | val geocode = getGeocode(name) 23 | // pair result 24 | Pair(geocode.results[0].geometry!!.location!!, name) 25 | }.toMap() // direct to map 26 | } 27 | 28 | override fun getGeocode(name: String): Geocode = gson.fromJson(readJsonFile(geocode_prefix + name + json_file), Geocode::class.java) 29 | 30 | override fun getWeather(name: String): Weather = gson.fromJson(readJsonFile(weather_prefix + name + json_file), Weather::class.java) 31 | 32 | abstract fun getAllFiles(): List 33 | 34 | abstract fun readJsonFile(jsonFile: String): String 35 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/local/JavaReader.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.local 2 | 3 | import java.io.File 4 | 5 | /** 6 | * Java Json reader for Tests 7 | */ 8 | class JavaReader : BaseReader() { 9 | 10 | fun basePath(): String? { 11 | val classLoader: ClassLoader = JavaReader::class.java.classLoader 12 | return classLoader.getResource("json/")?.path 13 | } 14 | 15 | override fun getAllFiles(): List { 16 | return basePath()?.let { 17 | val list = File(it).list() 18 | list.toList() 19 | }!! 20 | } 21 | 22 | override fun readJsonFile(jsonFile: String): String = 23 | File("${basePath()}/$jsonFile").readLines().joinToString(separator = "\n") 24 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/local/JsonReader.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.local 2 | 3 | import fr.ekito.myweatherapp.data.datasource.webservice.json.geocode.Geocode 4 | import fr.ekito.myweatherapp.data.datasource.webservice.json.geocode.Location 5 | import fr.ekito.myweatherapp.data.datasource.webservice.json.weather.Weather 6 | 7 | /** 8 | * Json reader 9 | */ 10 | interface JsonReader { 11 | fun getAllLocations(): Map 12 | fun getWeather(name: String): Weather 13 | fun getGeocode(name: String): Geocode 14 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/datasource/webservice/local/LocalFileDataSource.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.datasource.webservice.local 2 | 3 | import fr.ekito.myweatherapp.data.datasource.webservice.WeatherWebDatasource 4 | import fr.ekito.myweatherapp.data.datasource.webservice.json.geocode.Geocode 5 | import fr.ekito.myweatherapp.data.datasource.webservice.json.weather.Weather 6 | import kotlinx.coroutines.experimental.Deferred 7 | import kotlinx.coroutines.experimental.async 8 | import kotlinx.coroutines.experimental.delay 9 | import java.util.concurrent.TimeUnit 10 | 11 | /** 12 | * Read json files and render weather date 13 | */ 14 | class LocalFileDataSource(val jsonReader: JsonReader, val delayed: Boolean) : 15 | WeatherWebDatasource { 16 | 17 | private val cities by lazy { jsonReader.getAllLocations() } 18 | 19 | private fun isKnownCity(address: String): Boolean = cities.values.contains(address) 20 | 21 | private fun cityFromLocation(lat: Double?, lng: Double?): String { 22 | return cities.filterKeys { it.lat == lat && it.lng == lng }.values.firstOrNull() 23 | ?: DEFAULT_CITY 24 | } 25 | 26 | override fun geocode(address: String): Deferred = async { 27 | val addressToLC = address.toLowerCase() 28 | val geocode = if (isKnownCity(addressToLC)) { 29 | jsonReader.getGeocode(addressToLC) 30 | } else { 31 | jsonReader.getGeocode(DEFAULT_CITY) 32 | } 33 | if (delayed) { 34 | delay(1, TimeUnit.SECONDS) 35 | } 36 | geocode 37 | } 38 | 39 | override fun weather(lat: Double?, lon: Double?, lang: String): Deferred = async { 40 | val city = cityFromLocation(lat, lon) 41 | val weather = jsonReader.getWeather(city) 42 | if (delayed) { 43 | delay(1, TimeUnit.SECONDS) 44 | } 45 | weather 46 | } 47 | 48 | companion object { 49 | const val DEFAULT_CITY = "toulouse" 50 | } 51 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/data/repository/WeatherRepository.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.data.repository 2 | 3 | import fr.ekito.myweatherapp.data.datasource.room.WeatherDAO 4 | import fr.ekito.myweatherapp.data.datasource.room.WeatherEntity 5 | import fr.ekito.myweatherapp.data.datasource.webservice.WeatherWebDatasource 6 | import fr.ekito.myweatherapp.data.datasource.webservice.json.geocode.getLocation 7 | import fr.ekito.myweatherapp.data.datasource.webservice.json.weather.getDailyForecasts 8 | import fr.ekito.myweatherapp.domain.DailyForecastModel 9 | import kotlinx.coroutines.experimental.Deferred 10 | import kotlinx.coroutines.experimental.async 11 | import java.util.* 12 | 13 | /** 14 | * Weather repository 15 | */ 16 | interface WeatherRepository { 17 | /** 18 | * Get weather from given location 19 | * if location is null, get last weather or default 20 | */ 21 | fun getWeather(location: String? = null): Deferred> 22 | 23 | /** 24 | * Get weather for given id 25 | */ 26 | fun getWeatherDetail(id: String): Deferred 27 | } 28 | 29 | /** 30 | * Weather repository 31 | * Make use of WeatherWebDatasource & add some cache 32 | */ 33 | class WeatherRepositoryImpl( 34 | private val weatherDatasource: WeatherWebDatasource, 35 | private val weatherDAO: WeatherDAO 36 | ) : WeatherRepository { 37 | 38 | override fun getWeatherDetail(id: String): Deferred = async { 39 | DailyForecastModel.from(weatherDAO.findWeatherById(id)) 40 | } 41 | 42 | private fun getWeatherFromLatest(latest: WeatherEntity): Deferred> = 43 | async { 44 | weatherDAO.findAllBy(latest.location, latest.date) 45 | .map { 46 | DailyForecastModel.from(it) 47 | } 48 | } 49 | 50 | override fun getWeather( 51 | location: String? 52 | ): Deferred> = async { 53 | val req = if (location == null) { 54 | val latest = weatherDAO.findLatestWeather() 55 | if (latest.isEmpty()) getNewWeather(DEFAULT_LOCATION) 56 | else getWeatherFromLatest(latest.first()) 57 | } else { 58 | getNewWeather(location) 59 | } 60 | req.await() 61 | } 62 | 63 | private fun getNewWeather(location: String): Deferred> = async { 64 | val now = Date() 65 | val loc = weatherDatasource.geocode(location).await().getLocation() ?: error("No Location date") 66 | val geoloc = weatherDatasource.weather(loc.lat, loc.lng, DEFAULT_LANG).await() 67 | val list = geoloc.getDailyForecasts(location) 68 | async { 69 | weatherDAO.saveAll(list.map { item -> WeatherEntity.from(item, now) }) 70 | } 71 | list 72 | } 73 | 74 | companion object { 75 | const val DEFAULT_LOCATION = "Paris" 76 | const val DEFAULT_LANG = "EN" 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/di/app_module.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.di 2 | 3 | import android.arch.persistence.room.Room 4 | import fr.ekito.myweatherapp.data.datasource.room.WeatherDatabase 5 | import fr.ekito.myweatherapp.data.repository.WeatherRepository 6 | import fr.ekito.myweatherapp.data.repository.WeatherRepositoryImpl 7 | import fr.ekito.myweatherapp.util.rx.ApplicationSchedulerProvider 8 | import fr.ekito.myweatherapp.util.rx.SchedulerProvider 9 | import fr.ekito.myweatherapp.view.detail.DetailViewModel 10 | import fr.ekito.myweatherapp.view.splash.SplashViewModel 11 | import fr.ekito.myweatherapp.view.weather.WeatherViewModel 12 | import org.koin.android.architecture.ext.viewModel 13 | import org.koin.android.ext.koin.androidApplication 14 | import org.koin.dsl.module.applicationContext 15 | 16 | /** 17 | * App Components 18 | */ 19 | val weatherAppModule = applicationContext { 20 | 21 | viewModel { DetailViewModel(get(), get()) } 22 | 23 | // ViewModel for Search View 24 | viewModel { SplashViewModel(get(), get()) } 25 | 26 | // WeatherViewModel declaration for Weather View components 27 | viewModel { WeatherViewModel(get(), get()) } 28 | 29 | // Weather Data Repository 30 | bean { WeatherRepositoryImpl(get(), get()) as WeatherRepository } 31 | 32 | // Rx Schedulers 33 | bean { ApplicationSchedulerProvider() as SchedulerProvider } 34 | 35 | // Room Database 36 | bean { 37 | Room.databaseBuilder(androidApplication(), WeatherDatabase::class.java, "weather-db") 38 | .build() 39 | } 40 | 41 | // Expose WeatherDAO directly 42 | bean { get().weatherDAO() } 43 | } 44 | 45 | // Gather all app modules 46 | val onlineWeatherApp = listOf(weatherAppModule, remoteDatasourceModule) 47 | val offlineWeatherApp = listOf(weatherAppModule, localAndroidDatasourceModule) -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/di/local_datasource_module.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.di 2 | 3 | import fr.ekito.myweatherapp.data.datasource.webservice.WeatherWebDatasource 4 | import fr.ekito.myweatherapp.data.datasource.local.AndroidJsonReader 5 | import fr.ekito.myweatherapp.data.datasource.webservice.local.JsonReader 6 | import fr.ekito.myweatherapp.data.datasource.webservice.local.LocalFileDataSource 7 | import org.koin.android.ext.koin.androidApplication 8 | import org.koin.dsl.module.applicationContext 9 | 10 | /** 11 | * Local Json Files Datasource 12 | */ 13 | val localAndroidDatasourceModule = applicationContext { 14 | bean { AndroidJsonReader(androidApplication()) as JsonReader } 15 | bean { LocalFileDataSource(get(), true) as WeatherWebDatasource } 16 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/di/remote_datasource_module.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.di 2 | 3 | import fr.ekito.myweatherapp.data.datasource.webservice.WeatherWebDatasource 4 | import fr.ekito.myweatherapp.di.DatasourceProperties.SERVER_URL 5 | import okhttp3.OkHttpClient 6 | import okhttp3.logging.HttpLoggingInterceptor 7 | import org.koin.dsl.module.applicationContext 8 | import retrofit2.Retrofit 9 | import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory 10 | import retrofit2.converter.gson.GsonConverterFactory 11 | import java.util.concurrent.TimeUnit 12 | 13 | /** 14 | * Remote Web Service datasource 15 | */ 16 | val remoteDatasourceModule = applicationContext { 17 | // provided web components 18 | bean { createOkHttpClient() } 19 | // Fill property 20 | bean { createWebService(get(), getProperty(SERVER_URL)) } 21 | } 22 | 23 | 24 | object DatasourceProperties { 25 | const val SERVER_URL = "SERVER_URL" 26 | } 27 | 28 | fun createOkHttpClient(): OkHttpClient { 29 | val httpLoggingInterceptor = HttpLoggingInterceptor() 30 | httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BASIC 31 | return OkHttpClient.Builder() 32 | .connectTimeout(60L, TimeUnit.SECONDS) 33 | .readTimeout(60L, TimeUnit.SECONDS) 34 | .addInterceptor(httpLoggingInterceptor).build() 35 | } 36 | 37 | inline fun createWebService(okHttpClient: OkHttpClient, url: String): T { 38 | val retrofit = Retrofit.Builder() 39 | .baseUrl(url) 40 | .client(okHttpClient) 41 | .addConverterFactory(GsonConverterFactory.create()) 42 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build() 43 | return retrofit.create(T::class.java) 44 | } 45 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/domain/DailyForecastModel.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.domain 2 | 3 | import fr.ekito.myweatherapp.data.datasource.room.WeatherEntity 4 | import fr.ekito.myweatherapp.data.datasource.webservice.json.weather.Forecastday_ 5 | import java.util.* 6 | 7 | /** 8 | * Represents our weather forecast for one day 9 | */ 10 | data class DailyForecastModel( 11 | val location: String, 12 | val day: String, 13 | val shortText: String, 14 | val fullText: String, 15 | val iconUrl: String, 16 | val icon: String, 17 | val temperature: Temperature, 18 | val wind: Wind, 19 | val humidity: Humidity, 20 | val id: String = UUID.randomUUID().toString() 21 | ) { 22 | val colorCode: Int by lazy { 23 | val avg = temperature.high.toInt() 24 | when { 25 | avg in 0..8 -> 1 26 | avg in 8..13 -> 2 27 | avg in 14..20 -> 3 28 | avg > 21 -> 4 29 | else -> 0 30 | } 31 | } 32 | 33 | companion object { 34 | fun from(location: String, f: Forecastday_) = DailyForecastModel( 35 | location, 36 | f.date?.weekday ?: "", 37 | f.conditions ?: "", 38 | "", 39 | f.iconUrl ?: "", 40 | getWeatherCode(f.icon ?: ""), 41 | Temperature(f.low?.celsius ?: "", f.high!!.celsius!!), 42 | Wind(f.avewind?.kph ?: 0, f.avewind?.dir ?: ""), 43 | Humidity(f.avehumidity ?: 0) 44 | ) 45 | 46 | fun from(entity: WeatherEntity) = DailyForecastModel( 47 | entity.location, 48 | entity.day, 49 | entity.shortText, 50 | entity.fullText, 51 | entity.iconUrl, 52 | entity.icon, 53 | Temperature(entity.temp_low, entity.temp_high), 54 | Wind(entity.wind_kph, entity.wind_dir), 55 | Humidity(entity.humidity), 56 | entity.id 57 | ) 58 | } 59 | } 60 | 61 | data class Wind(val kph: Int, val dir: String) { 62 | override fun toString(): String { 63 | return "$kph KPH $dir" 64 | } 65 | } 66 | 67 | data class Temperature(val low: String, val high: String) { 68 | 69 | override fun toString(): String { 70 | return "$low°C - $high°C" 71 | } 72 | } 73 | 74 | data class Humidity(val humidity: Int) { 75 | override fun toString(): String { 76 | return "$humidity %" 77 | } 78 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/domain/WeatherCode.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.domain 2 | 3 | import android.content.Context 4 | import fr.ekito.myweatherapp.R 5 | import fr.ekito.myweatherapp.view.weather.list.WeatherItem 6 | 7 | internal const val PREFIX = "nt_" 8 | 9 | const val CHANCE_FLURRIES = "chanceflurries" // wi-snow-wind 10 | const val CHANCE_RAIN = "chancerain" // wi-rain 11 | const val CHANCE_SLEET = "chancesleet" // wi-rain-mix 12 | const val CHANCE_SNOW = "chancesnow" // wi-snow 13 | const val CHANCE_STORMS = "chancestorms" // wi-thunderstorm 14 | 15 | const val CLEAR = "clear" // wi-day-sunny 16 | const val CLOUDY = "cloudy" // wi-cloudy 17 | const val FLURRIES = "flurries" // wi-snow-wind 18 | const val FOG = "fog" // wi-fog 19 | const val HAZY = "hazy" // wi-fog 20 | 21 | const val MOSTLY_CLOUDY = "mostlycloudy" // wi-day-cloudy 22 | const val MOSTLY_SUNNY = "mostlysunny" // wi-day-cloudy 23 | const val PARTLY_CLOUDY = "partlycloudy" // wi-day-cloudy 24 | const val PARTLY_SUNNY = "partlysunny" // wi-day-cloudy 25 | 26 | const val RAIN = "rain" // wi-rain 27 | const val SLEET = "sleet" // wi-rain-mix 28 | const val SNOW = "snow" // wi-snow 29 | const val SUNNY = "sunny" // wi-day-sunny 30 | const val TSTORMS = "tstorms" // wi-thunderstorm 31 | 32 | const val WI_SNOW_WIND = "{wi_snow_wind}" 33 | const val WI_RAIN = "{wi_rain}" 34 | const val WI_RAIN_MIX = "{wi_rain_mix}" 35 | const val WI_SNOW = "{wi_snow}" 36 | const val WI_THUNDERSTORM = "{wi_thunderstorm}" 37 | const val WI_DAY_SUNNY = "{wi_day_sunny}" 38 | const val WI_CLOUDY = "{wi_cloudy}" 39 | const val WI_FOG = "{wi_fog}" 40 | const val WI_DAY_CLOUDY = "{wi_day_cloudy}" 41 | 42 | fun getWeatherCode(icon: String): String { 43 | return when (icon) { 44 | CHANCE_STORMS, PREFIX + CHANCE_STORMS, TSTORMS, PREFIX + TSTORMS -> WI_THUNDERSTORM 45 | CHANCE_SNOW, PREFIX + CHANCE_SNOW, SNOW, PREFIX + SNOW -> WI_SNOW 46 | CHANCE_FLURRIES, PREFIX + CHANCE_FLURRIES, FLURRIES, PREFIX + FLURRIES -> WI_SNOW_WIND 47 | CHANCE_RAIN, PREFIX + CHANCE_RAIN, RAIN, PREFIX + RAIN -> WI_RAIN 48 | CHANCE_SLEET, PREFIX + CHANCE_SLEET, SLEET, PREFIX + SLEET -> WI_RAIN_MIX 49 | FOG, PREFIX + FOG, HAZY, PREFIX + HAZY -> WI_FOG 50 | CLOUDY, PREFIX + CLOUDY -> WI_CLOUDY 51 | MOSTLY_CLOUDY, PREFIX + MOSTLY_CLOUDY, MOSTLY_SUNNY, PREFIX + MOSTLY_SUNNY, PARTLY_CLOUDY, PREFIX + PARTLY_CLOUDY, PARTLY_SUNNY, PREFIX + PARTLY_SUNNY -> WI_DAY_CLOUDY 52 | CLEAR, PREFIX + CLEAR, SUNNY, PREFIX + SUNNY -> WI_DAY_SUNNY 53 | else -> WI_DAY_CLOUDY 54 | } 55 | } 56 | 57 | @Suppress("DEPRECATION") 58 | fun Context.getColorFromCode(w: DailyForecastModel): Int { 59 | return when (w.colorCode) { 60 | 1 -> resources.getColor(R.color.temp_1) 61 | 2 -> resources.getColor(R.color.temp_2) 62 | 3 -> resources.getColor(R.color.temp_3) 63 | 4 -> resources.getColor(R.color.temp_4) 64 | else -> resources.getColor(R.color.temp_0) 65 | } 66 | } 67 | 68 | @Suppress("DEPRECATION") 69 | fun Context.getColorFromCode(w: WeatherItem): Int { 70 | return when (w.color) { 71 | 1 -> resources.getColor(R.color.temp_1) 72 | 2 -> resources.getColor(R.color.temp_2) 73 | 3 -> resources.getColor(R.color.temp_3) 74 | 4 -> resources.getColor(R.color.temp_4) 75 | else -> resources.getColor(R.color.temp_0) 76 | } 77 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/util/ext/FragmentActivityExt.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("UNCHECKED_CAST") 2 | 3 | package fr.ekito.myweatherapp.util.ext 4 | 5 | import android.support.v4.app.FragmentActivity 6 | 7 | /** 8 | * Retrieve argument from Activity intent 9 | */ 10 | fun FragmentActivity.argument(key: String) = 11 | lazy { intent.extras[key] as? T ?: error("Intent Argument $key is missing") } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/util/mvp/BasePresenter.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.util.mvp 2 | 3 | /** 4 | * Presenter 5 | */ 6 | interface BasePresenter { 7 | 8 | fun subscribe(view: V) 9 | 10 | fun unSubscribe() 11 | 12 | var view : V? 13 | 14 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/util/mvp/BaseView.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.util.mvp 2 | 3 | /** 4 | * View 5 | */ 6 | interface BaseView> { 7 | 8 | fun showError(error: Throwable) 9 | 10 | val presenter: T 11 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/util/mvp/RxPresenter.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.util.mvp 2 | 3 | import android.support.annotation.CallSuper 4 | import io.reactivex.disposables.CompositeDisposable 5 | import io.reactivex.disposables.Disposable 6 | 7 | /** 8 | * Base Presenter feature - for Rx Jobs 9 | * 10 | * launch() - launch a Rx request 11 | * clear all request on stop 12 | */ 13 | abstract class RxPresenter : BasePresenter { 14 | 15 | private val disposables = CompositeDisposable() 16 | 17 | fun launch(job: () -> Disposable) { 18 | disposables.add(job()) 19 | } 20 | 21 | override fun subscribe(view: V) { 22 | this.view = view 23 | } 24 | 25 | @CallSuper 26 | override fun unSubscribe() { 27 | disposables.clear() 28 | view = null 29 | } 30 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/util/mvvm/RxViewModel.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.util.mvvm 2 | 3 | import android.arch.lifecycle.ViewModel 4 | import fr.ekito.myweatherapp.util.rx.SchedulerProvider 5 | import kotlinx.coroutines.experimental.CoroutineScope 6 | import kotlinx.coroutines.experimental.Job 7 | 8 | /** 9 | * ViewModel for Coroutines Jobs 10 | * 11 | * launch() - launch a Rx request 12 | * clear all request on stop 13 | */ 14 | abstract class RxViewModel(private val schedulerProvider: SchedulerProvider) : ViewModel() { 15 | var jobs = listOf() 16 | 17 | fun launch(code: suspend CoroutineScope.() -> Unit) { 18 | jobs += kotlinx.coroutines.experimental.launch(schedulerProvider.ui(), block = code) 19 | } 20 | 21 | override fun onCleared() { 22 | super.onCleared() 23 | jobs.forEach { it.cancel() } 24 | } 25 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/util/mvvm/SingleLiveEvent.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.util.mvvm 2 | 3 | import android.arch.lifecycle.LifecycleOwner 4 | import android.arch.lifecycle.MutableLiveData 5 | import android.arch.lifecycle.Observer 6 | import android.support.annotation.MainThread 7 | import android.util.Log 8 | import java.util.concurrent.atomic.AtomicBoolean 9 | 10 | /** 11 | Extracted from MVVM Google Blueprints Project - 12 | https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live-kotlin/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.kt 13 | */ 14 | 15 | /** 16 | * A lifecycle-aware observable that sends only new updates after subscription, used for events like 17 | * navigation and Snackbar messages. 18 | * 19 | * 20 | * This avoids a common problem with events: on configuration change (like rotation) an update 21 | * can be emitted if the observer is active. This LiveData only calls the observable if there's an 22 | * explicit call to setValue() or call(). 23 | * 24 | * 25 | * Note that only one observer is going to be notified of changes. 26 | */ 27 | class SingleLiveEvent : MutableLiveData() { 28 | 29 | private val pending = AtomicBoolean(false) 30 | 31 | @MainThread 32 | override fun observe(owner: LifecycleOwner, observer: Observer) { 33 | 34 | if (hasActiveObservers()) { 35 | Log.w(TAG, "Multiple observers registered but only one will be notified of changes.") 36 | } 37 | 38 | // Observe the internal MutableLiveData 39 | super.observe(owner, Observer { t -> 40 | if (pending.compareAndSet(true, false)) { 41 | observer.onChanged(t) 42 | } 43 | }) 44 | } 45 | 46 | @MainThread 47 | override fun setValue(t: T?) { 48 | pending.set(true) 49 | super.setValue(t) 50 | } 51 | 52 | /** 53 | * Used for cases where T is Void, to make calls cleaner. 54 | */ 55 | @MainThread 56 | fun call() { 57 | value = null 58 | } 59 | 60 | companion object { 61 | private const val TAG = "SingleLiveEvent" 62 | } 63 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/util/rx/ApplicationSchedulerProvider.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.util.rx 2 | 3 | import kotlinx.coroutines.experimental.android.UI 4 | 5 | /** 6 | * Application providers 7 | */ 8 | class ApplicationSchedulerProvider : SchedulerProvider { 9 | override fun ui() = UI 10 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/util/rx/SchedulerProvider.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.util.rx 2 | 3 | import kotlinx.coroutines.experimental.CoroutineDispatcher 4 | 5 | /** 6 | * Rx Scheduler Provider 7 | */ 8 | interface SchedulerProvider { 9 | fun ui(): CoroutineDispatcher 10 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/Events.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view 2 | 3 | /** 4 | * Abstract Event from ViewModel 5 | */ 6 | open class Event 7 | 8 | /** 9 | * Generic Loading Event 10 | */ 11 | object LoadingEvent : Event() 12 | 13 | /** 14 | * Generic Success Event 15 | */ 16 | object SuccessEvent : Event() 17 | 18 | /** 19 | * Generic Failed Event 20 | */ 21 | data class FailedEvent(val error: Throwable) : Event() -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/IntentArguments.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view 2 | 3 | object IntentArguments { 4 | const val ARG_WEATHER_ITEM_ID: String = "WEATHER_ID" 5 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/States.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view 2 | 3 | /** 4 | * Abstract State 5 | */ 6 | open class State 7 | 8 | /** 9 | * Generic Loading State 10 | */ 11 | object LoadingState : State() 12 | 13 | /** 14 | * Generic Error state 15 | * @param error - caught error 16 | */ 17 | data class ErrorState(val error: Throwable) : State() 18 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/detail/DetailActivity.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.detail 2 | 3 | import android.arch.lifecycle.Observer 4 | import android.os.Bundle 5 | import android.support.design.widget.Snackbar 6 | import android.support.v7.app.AppCompatActivity 7 | import fr.ekito.myweatherapp.R 8 | import fr.ekito.myweatherapp.domain.DailyForecastModel 9 | import fr.ekito.myweatherapp.domain.getColorFromCode 10 | import fr.ekito.myweatherapp.util.ext.argument 11 | import fr.ekito.myweatherapp.view.ErrorState 12 | import fr.ekito.myweatherapp.view.IntentArguments.ARG_WEATHER_ITEM_ID 13 | import kotlinx.android.synthetic.main.activity_detail.* 14 | import org.koin.android.architecture.ext.viewModel 15 | 16 | /** 17 | * Weather Detail View 18 | */ 19 | class DetailActivity : AppCompatActivity() { 20 | 21 | // Detail id passed by argument 22 | private val detailId by argument(ARG_WEATHER_ITEM_ID) 23 | 24 | private val viewModel by viewModel() 25 | 26 | override fun onCreate(savedInstanceState: Bundle?) { 27 | super.onCreate(savedInstanceState) 28 | setContentView(R.layout.activity_detail) 29 | // Observe States 30 | viewModel.states.observe(this, Observer { state -> 31 | state?.let { 32 | when (state) { 33 | is ErrorState -> showError(state.error) 34 | is DetailViewModel.WeatherDetailState -> showDetail(state.weather) 35 | } 36 | } 37 | }) 38 | viewModel.getDetail(detailId) 39 | } 40 | 41 | private fun showError(error: Throwable) { 42 | Snackbar.make( 43 | weatherItem, 44 | getString(R.string.loading_error) + " $error", 45 | Snackbar.LENGTH_LONG 46 | ).show() 47 | } 48 | 49 | private fun showDetail(weather: DailyForecastModel) { 50 | weatherIcon.text = weather.icon 51 | weatherDay.text = weather.day 52 | weatherText.text = weather.fullText 53 | weatherWindText.text = weather.wind.toString() 54 | weatherTempText.text = weather.temperature.toString() 55 | weatherHumidityText.text = weather.humidity.toString() 56 | weatherItem.background.setTint(getColorFromCode(weather)) 57 | // Set back on background click 58 | weatherItem.setOnClickListener { 59 | onBackPressed() 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/detail/DetailViewModel.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.detail 2 | 3 | import android.arch.lifecycle.LiveData 4 | import android.arch.lifecycle.MutableLiveData 5 | import fr.ekito.myweatherapp.data.repository.WeatherRepository 6 | import fr.ekito.myweatherapp.domain.DailyForecastModel 7 | import fr.ekito.myweatherapp.util.mvvm.RxViewModel 8 | import fr.ekito.myweatherapp.util.rx.SchedulerProvider 9 | import fr.ekito.myweatherapp.view.ErrorState 10 | import fr.ekito.myweatherapp.view.LoadingState 11 | import fr.ekito.myweatherapp.view.State 12 | 13 | class DetailViewModel( 14 | private val weatherRepository: WeatherRepository, 15 | schedulerProvider: SchedulerProvider 16 | ) : RxViewModel(schedulerProvider) { 17 | 18 | private val mStates = MutableLiveData() 19 | val states: LiveData 20 | get() = mStates 21 | 22 | fun getDetail(id: String) { 23 | mStates.value = LoadingState 24 | launch { 25 | try { 26 | val detail = weatherRepository.getWeatherDetail(id).await() 27 | mStates.value = WeatherDetailState(detail) 28 | } catch (error: Throwable) { 29 | mStates.value = ErrorState(error) 30 | } 31 | } 32 | } 33 | 34 | data class WeatherDetailState(val weather: DailyForecastModel) : State() 35 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/splash/SplashActivity.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.splash 2 | 3 | import android.arch.lifecycle.Observer 4 | import android.os.Bundle 5 | import android.support.design.widget.Snackbar 6 | import android.support.v7.app.AppCompatActivity 7 | import android.view.View 8 | import android.view.animation.AnimationUtils 9 | import fr.ekito.myweatherapp.R 10 | import fr.ekito.myweatherapp.view.FailedEvent 11 | import fr.ekito.myweatherapp.view.LoadingEvent 12 | import fr.ekito.myweatherapp.view.SuccessEvent 13 | import fr.ekito.myweatherapp.view.weather.WeatherActivity 14 | import kotlinx.android.synthetic.main.activity_splash.* 15 | import org.jetbrains.anko.clearTask 16 | import org.jetbrains.anko.clearTop 17 | import org.jetbrains.anko.intentFor 18 | import org.jetbrains.anko.newTask 19 | import org.koin.android.architecture.ext.viewModel 20 | 21 | /** 22 | * Search Weather View 23 | */ 24 | class SplashActivity : AppCompatActivity() { 25 | 26 | // Declare SplashViewModel with Koin and allow constructor dependency injection 27 | private val viewModel by viewModel() 28 | 29 | override fun onCreate(savedInstanceState: Bundle?) { 30 | super.onCreate(savedInstanceState) 31 | setContentView(R.layout.activity_splash) 32 | 33 | viewModel.events.observe(this, Observer { event -> 34 | event?.let { 35 | when (event) { 36 | LoadingEvent -> showIsLoading() 37 | SuccessEvent -> showIsLoaded() 38 | is FailedEvent -> showError(event.error) 39 | } 40 | } 41 | }) 42 | viewModel.getLastWeather() 43 | } 44 | 45 | private fun showIsLoading() { 46 | val animation = 47 | AnimationUtils.loadAnimation(applicationContext, R.anim.infinite_blinking_animation) 48 | splashIcon.startAnimation(animation) 49 | } 50 | 51 | private fun showIsLoaded() { 52 | startActivity(intentFor().clearTop().clearTask().newTask()) 53 | } 54 | 55 | private fun showError(error: Throwable) { 56 | splashIcon.visibility = View.GONE 57 | splashIconFail.visibility = View.VISIBLE 58 | Snackbar.make( 59 | splash, 60 | getString(R.string.loading_error) + " $error", 61 | Snackbar.LENGTH_INDEFINITE 62 | ) 63 | .setAction(R.string.retry, { 64 | viewModel.getLastWeather() 65 | }) 66 | .show() 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/splash/SplashViewModel.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.splash 2 | 3 | import android.arch.lifecycle.LiveData 4 | import fr.ekito.myweatherapp.data.repository.WeatherRepository 5 | import fr.ekito.myweatherapp.util.mvvm.RxViewModel 6 | import fr.ekito.myweatherapp.util.mvvm.SingleLiveEvent 7 | import fr.ekito.myweatherapp.util.rx.SchedulerProvider 8 | import fr.ekito.myweatherapp.view.Event 9 | import fr.ekito.myweatherapp.view.FailedEvent 10 | import fr.ekito.myweatherapp.view.LoadingEvent 11 | import fr.ekito.myweatherapp.view.SuccessEvent 12 | 13 | class SplashViewModel( 14 | private val weatherRepository: WeatherRepository, 15 | schedulerProvider: SchedulerProvider 16 | ) : RxViewModel(schedulerProvider) { 17 | 18 | /* 19 | * We use SingleLiveEvent to publish "events" 20 | * No need to publish and retain any view state 21 | */ 22 | private val mEvents = SingleLiveEvent() 23 | val events: LiveData 24 | get() = mEvents 25 | 26 | fun getLastWeather() { 27 | mEvents.value = LoadingEvent 28 | launch { 29 | try { 30 | weatherRepository.getWeather().await() 31 | mEvents.value = SuccessEvent 32 | } catch (error: Throwable) { 33 | mEvents.value = FailedEvent(error) 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/weather/WeatherActivity.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.weather 2 | 3 | import android.arch.lifecycle.Observer 4 | import android.os.Bundle 5 | import android.support.design.widget.Snackbar 6 | import android.support.v7.app.AppCompatActivity 7 | import android.util.Log 8 | import android.view.View 9 | import fr.ekito.myweatherapp.R 10 | import fr.ekito.myweatherapp.view.ErrorState 11 | import kotlinx.android.synthetic.main.activity_result.* 12 | import org.jetbrains.anko.clearTask 13 | import org.jetbrains.anko.clearTop 14 | import org.jetbrains.anko.intentFor 15 | import org.jetbrains.anko.newTask 16 | import org.koin.android.architecture.ext.viewModel 17 | 18 | /** 19 | * Weather Result View 20 | */ 21 | class WeatherActivity : AppCompatActivity() { 22 | 23 | /* 24 | * Declare WeatherViewModel with Koin and allow constructor dependency injection 25 | */ 26 | private val viewModel by viewModel() 27 | 28 | val TAG = this::class.java.simpleName 29 | 30 | override fun onCreate(savedInstanceState: Bundle?) { 31 | super.onCreate(savedInstanceState) 32 | setContentView(R.layout.activity_result) 33 | 34 | val weatherTitleFragment = WeatherHeaderFragment() 35 | val resultListFragment = WeatherListFragment() 36 | 37 | supportFragmentManager 38 | .beginTransaction() 39 | .replace(R.id.weather_title, weatherTitleFragment) 40 | .commit() 41 | supportFragmentManager 42 | .beginTransaction() 43 | .replace(R.id.weather_list, resultListFragment) 44 | .commit() 45 | 46 | // Observe ErrorState 47 | viewModel.states.observe(this, Observer { state -> 48 | state?.let { 49 | when (state) { 50 | is ErrorState -> showError(state.error) 51 | } 52 | } 53 | }) 54 | // Launch load of weather data 55 | viewModel.getWeather() 56 | } 57 | 58 | private fun showError(error: Throwable) { 59 | Log.e(TAG, "error $error while displaying weather") 60 | weather_views.visibility = View.GONE 61 | weather_error.visibility = View.VISIBLE 62 | Snackbar.make( 63 | weather_result, 64 | getString(R.string.loading_error) + " $error", 65 | Snackbar.LENGTH_INDEFINITE 66 | ) 67 | .setAction(R.string.retry, { 68 | startActivity(intentFor().clearTop().clearTask().newTask()) 69 | }) 70 | .show() 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/weather/WeatherHeaderFragment.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.weather 2 | 3 | import android.app.AlertDialog 4 | import android.arch.lifecycle.Observer 5 | import android.os.Bundle 6 | import android.support.design.widget.Snackbar 7 | import android.support.v4.app.Fragment 8 | import android.text.InputType 9 | import android.view.LayoutInflater 10 | import android.view.View 11 | import android.view.ViewGroup 12 | import android.widget.EditText 13 | import fr.ekito.myweatherapp.R 14 | import fr.ekito.myweatherapp.domain.DailyForecastModel 15 | import fr.ekito.myweatherapp.domain.getColorFromCode 16 | import fr.ekito.myweatherapp.view.IntentArguments 17 | import fr.ekito.myweatherapp.view.detail.DetailActivity 18 | import kotlinx.android.synthetic.main.fragment_result_header.* 19 | import org.jetbrains.anko.startActivity 20 | import org.koin.android.architecture.ext.sharedViewModel 21 | 22 | class WeatherHeaderFragment : Fragment() { 23 | 24 | /* 25 | * Declare shared WeatherViewModel with WeatherActivity 26 | */ 27 | private val viewModel by sharedViewModel() 28 | 29 | override fun onCreateView( 30 | inflater: LayoutInflater, 31 | container: ViewGroup?, 32 | savedInstanceState: Bundle? 33 | ): View { 34 | return inflater.inflate(R.layout.fragment_result_header, container, false) as ViewGroup 35 | } 36 | 37 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 38 | super.onViewCreated(view, savedInstanceState) 39 | // Observe WeatherListState 40 | viewModel.states.observe(this, Observer { state -> 41 | state?.let { 42 | when (state) { 43 | is WeatherViewModel.WeatherListState -> showWeather(state.location, state.first) 44 | } 45 | } 46 | }) 47 | // Observe LoadingLocationEvent & LoadLocationFailedEvent 48 | viewModel.events.observe(this, Observer { event -> 49 | event?.let { 50 | when (event) { 51 | is WeatherViewModel.LoadingLocationEvent -> showLoadingLocation(event.location) 52 | is WeatherViewModel.LoadLocationFailedEvent -> showLocationSearchFailed( 53 | event.location, 54 | event.error 55 | ) 56 | } 57 | } 58 | }) 59 | } 60 | 61 | private fun showWeather(location: String, weather: DailyForecastModel) { 62 | weatherCity.text = location 63 | weatherCityCard.setOnClickListener { 64 | promptLocationDialog() 65 | } 66 | 67 | weatherIcon.text = weather.icon 68 | weatherDay.text = weather.day 69 | weatherTempText.text = weather.temperature.toString() 70 | weatherText.text = weather.shortText 71 | 72 | val color = context!!.getColorFromCode(weather) 73 | weatherHeader.background.setTint(color) 74 | 75 | weatherHeader.setOnClickListener { 76 | activity?.startActivity( 77 | IntentArguments.ARG_WEATHER_ITEM_ID to weather.id 78 | ) 79 | } 80 | } 81 | 82 | private fun promptLocationDialog() { 83 | val dialog = AlertDialog.Builder(context) 84 | dialog.setTitle(getString(R.string.enter_location)) 85 | val editText = EditText(context) 86 | editText.hint = getString(R.string.location_hint) 87 | editText.maxLines = 1 88 | editText.inputType = InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS 89 | dialog.setView(editText) 90 | dialog.setPositiveButton(getString(R.string.search)) { dialogInterface, _ -> 91 | dialogInterface.dismiss() 92 | val newLocation = editText.text.trim().toString() 93 | viewModel.loadNewLocation(newLocation) 94 | } 95 | dialog.setNegativeButton(getString(R.string.cancel)) { dialogInterface, _ -> 96 | dialogInterface.dismiss() 97 | } 98 | dialog.show() 99 | } 100 | 101 | private fun showLoadingLocation(location: String) { 102 | Snackbar.make( 103 | weatherHeader, 104 | getString(R.string.loading_location) + " $location ...", 105 | Snackbar.LENGTH_LONG 106 | ) 107 | .show() 108 | } 109 | 110 | private fun showLocationSearchFailed(location: String, error: Throwable) { 111 | Snackbar.make( 112 | weatherHeader, 113 | getString(R.string.loading_error) + " $error", 114 | Snackbar.LENGTH_LONG 115 | ) 116 | .setAction(R.string.retry, { 117 | viewModel.loadNewLocation(location) 118 | }) 119 | .show() 120 | } 121 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/weather/WeatherListFragment.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.weather 2 | 3 | import android.arch.lifecycle.Observer 4 | import android.os.Bundle 5 | import android.support.v4.app.Fragment 6 | import android.support.v7.widget.LinearLayoutManager 7 | import android.view.LayoutInflater 8 | import android.view.View 9 | import android.view.ViewGroup 10 | import fr.ekito.myweatherapp.R 11 | import fr.ekito.myweatherapp.view.IntentArguments 12 | import fr.ekito.myweatherapp.view.detail.DetailActivity 13 | import fr.ekito.myweatherapp.view.weather.list.WeatherItem 14 | import fr.ekito.myweatherapp.view.weather.list.WeatherListAdapter 15 | import kotlinx.android.synthetic.main.fragment_result_list.* 16 | import org.jetbrains.anko.startActivity 17 | import org.koin.android.architecture.ext.sharedViewModel 18 | 19 | class WeatherListFragment : Fragment() { 20 | 21 | /* 22 | * Declare shared WeatherViewModel with WeatherActivity 23 | */ 24 | private val viewModel by sharedViewModel() 25 | 26 | override fun onCreateView( 27 | inflater: LayoutInflater, 28 | container: ViewGroup?, 29 | savedInstanceState: Bundle? 30 | ): View? { 31 | return inflater.inflate(R.layout.fragment_result_list, container, false) 32 | } 33 | 34 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 35 | super.onViewCreated(view, savedInstanceState) 36 | prepareListView() 37 | // Observe WeatherListState 38 | viewModel.states.observe(this, Observer { state -> 39 | state?.let { 40 | when (state) { 41 | is WeatherViewModel.WeatherListState -> showWeatherItemList(state.lasts.map { 42 | WeatherItem.from( 43 | it 44 | ) 45 | }) 46 | } 47 | } 48 | }) 49 | } 50 | 51 | private fun prepareListView() { 52 | weatherList.layoutManager = 53 | LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false) 54 | weatherList.adapter = WeatherListAdapter( 55 | activity!!, 56 | emptyList(), 57 | ::onWeatherItemSelected 58 | ) 59 | } 60 | 61 | private fun onWeatherItemSelected(resultItem: WeatherItem) { 62 | activity?.startActivity( 63 | IntentArguments.ARG_WEATHER_ITEM_ID to resultItem.id 64 | ) 65 | } 66 | 67 | private fun showWeatherItemList(newList: List) { 68 | val adapter: WeatherListAdapter = weatherList.adapter as WeatherListAdapter 69 | adapter.list = newList 70 | adapter.notifyDataSetChanged() 71 | } 72 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/weather/WeatherViewModel.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.weather 2 | 3 | import android.arch.lifecycle.LiveData 4 | import android.arch.lifecycle.MutableLiveData 5 | import fr.ekito.myweatherapp.data.repository.WeatherRepository 6 | import fr.ekito.myweatherapp.domain.DailyForecastModel 7 | import fr.ekito.myweatherapp.util.mvvm.RxViewModel 8 | import fr.ekito.myweatherapp.util.mvvm.SingleLiveEvent 9 | import fr.ekito.myweatherapp.util.rx.SchedulerProvider 10 | import fr.ekito.myweatherapp.view.ErrorState 11 | import fr.ekito.myweatherapp.view.Event 12 | import fr.ekito.myweatherapp.view.LoadingState 13 | import fr.ekito.myweatherapp.view.State 14 | 15 | class WeatherViewModel( 16 | private val weatherRepository: WeatherRepository, 17 | schedulerProvider: SchedulerProvider 18 | ) : RxViewModel(schedulerProvider) { 19 | 20 | private val mStates = MutableLiveData() 21 | val states: LiveData 22 | get() = mStates 23 | 24 | private val mEvents = SingleLiveEvent() 25 | val events: LiveData 26 | get() = mEvents 27 | 28 | /** 29 | * Load new weather for given location 30 | * notify for loading: LoadingLocationEvent / LoadLocationFailedEvent 31 | * push WeatherListState if it succeed 32 | */ 33 | fun loadNewLocation(newLocation: String) { 34 | launch { 35 | mEvents.value = LoadingLocationEvent(newLocation) 36 | try { 37 | val weather = weatherRepository.getWeather(newLocation).await() 38 | mStates.value = WeatherListState.from(weather) 39 | } catch (error: Throwable) { 40 | mEvents.value = LoadLocationFailedEvent(newLocation, error) 41 | } 42 | } 43 | } 44 | 45 | /** 46 | * Retrieve previously loaded weather and push view states 47 | */ 48 | fun getWeather() { 49 | launch { 50 | mStates.value = LoadingState 51 | try { 52 | val weather = weatherRepository.getWeather().await() 53 | mStates.value = WeatherListState.from(weather) 54 | } catch (error: Throwable) { 55 | mStates.value = ErrorState(error) 56 | } 57 | } 58 | } 59 | 60 | data class WeatherListState( 61 | val location: String, 62 | val first: DailyForecastModel, 63 | val lasts: List 64 | ) : State() { 65 | companion object { 66 | fun from(list: List): WeatherListState { 67 | return if (list.isEmpty()) error("weather list should not be empty") 68 | else { 69 | val first = list.first() 70 | val location = first.location 71 | WeatherListState(location, first, list.takeLast(list.size - 1)) 72 | } 73 | } 74 | } 75 | } 76 | 77 | data class LoadingLocationEvent(val location: String) : Event() 78 | data class LoadLocationFailedEvent(val location: String, val error: Throwable) : Event() 79 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/weather/list/WeatherItem.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.weather.list 2 | 3 | import fr.ekito.myweatherapp.domain.DailyForecastModel 4 | 5 | /** 6 | * Result Item - Display in ResultList View Adapter 7 | */ 8 | data class WeatherItem(val id: String, val day: String, val icon: String, val color : Int) { 9 | companion object { 10 | fun from(weather: DailyForecastModel) = WeatherItem( 11 | weather.id, 12 | weather.day, 13 | weather.icon, 14 | weather.colorCode 15 | ) 16 | } 17 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/weather/list/WeatherListAdapter.kt: -------------------------------------------------------------------------------- 1 | package fr.ekito.myweatherapp.view.weather.list 2 | 3 | import android.content.Context 4 | import android.support.v7.widget.RecyclerView 5 | import android.view.LayoutInflater 6 | import android.view.View 7 | import android.view.ViewGroup 8 | import android.widget.LinearLayout 9 | import android.widget.TextView 10 | import com.joanzapata.iconify.widget.IconTextView 11 | import fr.ekito.myweatherapp.R 12 | import fr.ekito.myweatherapp.domain.getColorFromCode 13 | 14 | class WeatherListAdapter( 15 | val context: Context, 16 | var list: List, 17 | private val onDetailSelected: (WeatherItem) -> Unit 18 | ) : RecyclerView.Adapter() { 19 | 20 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeatherResultHolder { 21 | val view = LayoutInflater.from(parent.context).inflate(R.layout.item_weather, parent, false) 22 | return WeatherResultHolder(view) 23 | } 24 | 25 | override fun onBindViewHolder(holder: WeatherResultHolder, position: Int) { 26 | holder.display(list[position], context, onDetailSelected) 27 | } 28 | 29 | override fun getItemCount() = list.size 30 | 31 | inner class WeatherResultHolder(item: View) : RecyclerView.ViewHolder(item) { 32 | private val weatherItemLayout = item.findViewById(R.id.weatherItemLayout) 33 | private val weatherItemDay = item.findViewById(R.id.weatheItemrDay) 34 | private val weatherItemIcon = item.findViewById(R.id.weatherItemIcon) 35 | 36 | fun display( 37 | dailyForecastModel: WeatherItem, 38 | context: Context, 39 | onClick: (WeatherItem) -> Unit 40 | ) { 41 | weatherItemLayout.setOnClickListener { onClick(dailyForecastModel) } 42 | weatherItemDay.text = dailyForecastModel.day 43 | weatherItemIcon.text = dailyForecastModel.icon 44 | val color = context.getColorFromCode(dailyForecastModel) 45 | weatherItemDay.setTextColor(color) 46 | weatherItemIcon.setTextColor(color) 47 | } 48 | 49 | } 50 | } -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/anim/infinite_blinking_animation.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/drawable/ic_edit_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/drawable/ic_edit_location_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/drawable/ic_location_on_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/drawable/ic_search_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/font/indieflower.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ekito/mvvm-coroutines/be37b060c9abe61717f26367e6957bd6e601dd64/weatherapp/app/src/main/res/font/indieflower.ttf -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/font/opensans_regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ekito/mvvm-coroutines/be37b060c9abe61717f26367e6957bd6e601dd64/weatherapp/app/src/main/res/font/opensans_regular.ttf -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/layout/activity_detail.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 26 | 27 | 44 | 45 | 63 | 64 | 65 | 77 | 78 | 94 | 95 | 96 | 108 | 109 | 124 | 125 | 126 | 138 | 139 | 154 | 155 | 161 | 162 | 168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/layout/activity_result.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 15 | 20 | 21 | 25 | 26 | 27 | 35 | 36 | 46 | 47 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/layout/activity_splash.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 22 | 23 | 32 | 33 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/layout/fragment_result_header.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 19 | 20 | 30 | 31 | 39 | 40 | 41 | 42 | 43 | 50 | 51 | 61 | 62 | 71 | 72 | 81 | 82 | 88 | 89 | 97 | 98 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/layout/fragment_result_list.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/layout/item_weather.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 16 | 17 | 23 | 24 | 34 | 35 | 44 | 45 | 46 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/menu/menu_main.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ekito/mvvm-coroutines/be37b060c9abe61717f26367e6957bd6e601dd64/weatherapp/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ekito/mvvm-coroutines/be37b060c9abe61717f26367e6957bd6e601dd64/weatherapp/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ekito/mvvm-coroutines/be37b060c9abe61717f26367e6957bd6e601dd64/weatherapp/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ekito/mvvm-coroutines/be37b060c9abe61717f26367e6957bd6e601dd64/weatherapp/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ekito/mvvm-coroutines/be37b060c9abe61717f26367e6957bd6e601dd64/weatherapp/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #2196F3 4 | #1976D2 5 | #BBDEFB 6 | #ffa000 7 | #ffa000 8 | 9 | #212121 10 | #777777 11 | #212121 12 | @color/accent_dark 13 | #BDBDBD 14 | 15 | #fa315b 16 | #e4e3e4 17 | #F5F5F5 18 | #FAFAFA 19 | #FFFFFF 20 | 21 | #455a64 22 | #42a5f5 23 | #26a69a 24 | #ffb74d 25 | #e57373 26 | 27 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 16dp 6 | 7 | 16dp 8 | 9 | 8dp 10 | 2dp 11 | 12 | 44dp 13 | 44dp 14 | 15 | 13sp 16 | 17 | 14sp 18 | 16sp 19 | 18sp 20 | 19sp 21 | 24sp 22 | 34sp 23 | 24 | 72dp 25 | 26 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | My Weather App 3 | Error while loading weather - 4 | Enter your location 5 | e.g: Paris 6 | SEARCH 7 | CANCEL 8 | Retry 9 | Loading location 10 | 11 | -------------------------------------------------------------------------------- /weatherapp/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 15 | 16 | 25 | 26 | 34 | 35 | 43 | 44 | 52 | 53 | 58 | 59 | 63 | 64 | 67 | 68 | 73 | 74 | 77 | 78 | 81 | 82 | 86 | 87 | 90 | 91 | 94 | 95 |