├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── app ├── src │ ├── main │ │ ├── res │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── values │ │ │ │ ├── dimens.xml │ │ │ │ ├── preloaded_fonts.xml │ │ │ │ ├── colors.xml │ │ │ │ ├── strings.xml │ │ │ │ ├── styles.xml │ │ │ │ └── font_certs.xml │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── font │ │ │ │ ├── work_sans.xml │ │ │ │ ├── work_sans_black.xml │ │ │ │ ├── work_sans_light.xml │ │ │ │ ├── work_sans_medium.xml │ │ │ │ ├── work_sans_extrabold.xml │ │ │ │ └── work_sans_semibold.xml │ │ │ ├── anim │ │ │ │ ├── slide_out_left.xml │ │ │ │ └── slide_in_right.xml │ │ │ ├── layout │ │ │ │ ├── main_activity.xml │ │ │ │ ├── forecasts_fragment.xml │ │ │ │ ├── forecast_item.xml │ │ │ │ └── weather_fragment.xml │ │ │ ├── navigation │ │ │ │ └── nav_graph.xml │ │ │ ├── drawable-v24 │ │ │ │ └── ic_launcher_foreground.xml │ │ │ └── drawable │ │ │ │ └── ic_launcher_background.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── arif │ │ │ │ └── kotlincoroutinesplusflow │ │ │ │ ├── features │ │ │ │ ├── home │ │ │ │ │ ├── di │ │ │ │ │ │ ├── HomeScope.kt │ │ │ │ │ │ ├── HomeComponent.kt │ │ │ │ │ │ └── HomeViewModelsModule.kt │ │ │ │ │ └── HomeActivity.kt │ │ │ │ ├── forecasts │ │ │ │ │ ├── ForecastsViewModel.kt │ │ │ │ │ ├── ForecastsAdapter.kt │ │ │ │ │ ├── ForecastsRepository.kt │ │ │ │ │ └── ForecastsFragment.kt │ │ │ │ └── weather │ │ │ │ │ ├── WeatherViewModel.kt │ │ │ │ │ ├── WeatherRepository.kt │ │ │ │ │ └── WeatherFragment.kt │ │ │ │ ├── network │ │ │ │ ├── response │ │ │ │ │ ├── ErrorResponse.kt │ │ │ │ │ ├── weather │ │ │ │ │ │ └── ApiWeather.kt │ │ │ │ │ └── forecast │ │ │ │ │ │ └── ApiForecast.kt │ │ │ │ └── api │ │ │ │ │ └── OpenWeatherApi.kt │ │ │ │ ├── room │ │ │ │ ├── models │ │ │ │ │ ├── utils │ │ │ │ │ │ └── StringKeyValuePair.kt │ │ │ │ │ ├── weather │ │ │ │ │ │ └── DbWeather.kt │ │ │ │ │ └── forecasts │ │ │ │ │ │ └── DbForecast.kt │ │ │ │ ├── dao │ │ │ │ │ ├── utils │ │ │ │ │ │ └── StringKeyValueDao.kt │ │ │ │ │ ├── weather │ │ │ │ │ │ └── WeatherDao.kt │ │ │ │ │ └── forecasts │ │ │ │ │ │ └── ForecastDao.kt │ │ │ │ └── db │ │ │ │ │ └── WeatherDatabase.kt │ │ │ │ ├── custom │ │ │ │ ├── errors │ │ │ │ │ ├── Exceptions.kt │ │ │ │ │ └── ErrorHandler.kt │ │ │ │ ├── aliases │ │ │ │ │ └── WeatherAppAliases.kt │ │ │ │ └── views │ │ │ │ │ ├── IndefiniteSnackbar.kt │ │ │ │ │ └── SpacesItemDecoration.kt │ │ │ │ ├── di │ │ │ │ ├── modules │ │ │ │ │ ├── SubcomponentsModule.kt │ │ │ │ │ ├── AppModule.kt │ │ │ │ │ ├── DbModule.kt │ │ │ │ │ └── OpenWeatherApiModule.kt │ │ │ │ ├── ViewModelKey.kt │ │ │ │ ├── components │ │ │ │ │ └── ApplicationComponent.kt │ │ │ │ └── factories │ │ │ │ │ └── WeatherViewModelFactory.kt │ │ │ │ ├── base │ │ │ │ ├── Result.kt │ │ │ │ └── BaseFragment.kt │ │ │ │ ├── entitymappers │ │ │ │ ├── Mapper.kt │ │ │ │ ├── weather │ │ │ │ │ └── WeatherMapper.kt │ │ │ │ └── forecasts │ │ │ │ │ └── ForecastMapper.kt │ │ │ │ ├── WeatherApplication.kt │ │ │ │ ├── utils │ │ │ │ └── Utils.kt │ │ │ │ └── extensions │ │ │ │ └── Extensions.kt │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── arif │ │ │ └── kotlincoroutinesplusflow │ │ │ └── ExampleUnitTest.kt │ └── androidTest │ │ └── java │ │ └── com │ │ └── arif │ │ └── kotlincoroutinesplusflow │ │ └── ExampleInstrumentedTest.kt ├── .gitignore ├── proguard-rules.pro ├── build.gradle └── schemas │ └── com.arif.kotlincoroutinesplusflow.room.db.WeatherDatabase │ └── 1.json ├── gradle.properties ├── README.md ├── .gitignore ├── gradlew.bat ├── gradlew └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | rootProject.name='KotlinCoroutinesPlusFlow' 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arifnadeem7/mvvmcoroutinesandflow/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8dp 4 | 16dp 5 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/home/di/HomeScope.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.home.di 2 | 3 | import javax.inject.Scope 4 | 5 | @Scope 6 | @Retention(value = AnnotationRetention.RUNTIME) 7 | annotation class HomeScope 8 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Sep 13 14:41:58 IST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip 7 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/network/response/ErrorResponse.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.network.response 2 | 3 | import com.squareup.moshi.JsonClass 4 | 5 | 6 | @JsonClass(generateAdapter = true) 7 | data class ErrorResponse(val cod: Int, val message: String) -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/room/models/utils/StringKeyValuePair.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.room.models.utils 2 | 3 | import androidx.room.Entity 4 | 5 | @Entity(primaryKeys = ["key"]) 6 | data class StringKeyValuePair( 7 | val key: String, val value: String 8 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/custom/errors/Exceptions.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.custom.errors 2 | 3 | class NoResponseException(message: String? = ErrorHandler.UNKNOWN_ERROR) : Exception(message) 4 | 5 | class NoDataException(message: String? = ErrorHandler.NO_SUCH_DATA) : Exception() -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/di/modules/SubcomponentsModule.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.di.modules 2 | 3 | import com.arif.kotlincoroutinesplusflow.features.home.di.HomeComponent 4 | import dagger.Module 5 | 6 | @Module(subcomponents = [HomeComponent::class]) 7 | class SubcomponentsModule -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/font/work_sans.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_out_left.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/anim/slide_in_right.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/di/modules/AppModule.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.di.modules 2 | 3 | import android.content.Context 4 | import dagger.Module 5 | import dagger.Provides 6 | import javax.inject.Singleton 7 | 8 | 9 | @Module 10 | class AppModule constructor(private val context: Context) { 11 | 12 | @Provides 13 | @Singleton 14 | fun provideAppContext() = context 15 | } -------------------------------------------------------------------------------- /app/src/main/res/font/work_sans_black.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/font/work_sans_light.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/font/work_sans_medium.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/font/work_sans_extrabold.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/font/work_sans_semibold.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/res/values/preloaded_fonts.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | @font/work_sans 5 | @font/work_sans_black 6 | @font/work_sans_extrabold 7 | @font/work_sans_light 8 | @font/work_sans_medium 9 | @font/work_sans_semibold 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/layout/main_activity.xml: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/di/ViewModelKey.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.di 2 | 3 | import androidx.lifecycle.ViewModel 4 | import dagger.MapKey 5 | import kotlin.reflect.KClass 6 | 7 | @MustBeDocumented 8 | @Target( 9 | AnnotationTarget.FUNCTION, 10 | AnnotationTarget.PROPERTY_GETTER, 11 | AnnotationTarget.PROPERTY_SETTER 12 | ) 13 | @Retention(AnnotationRetention.RUNTIME) 14 | @MapKey 15 | annotation class ViewModelKey(val value: KClass) -------------------------------------------------------------------------------- /app/src/test/java/com/arif/kotlincoroutinesplusflow/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow 2 | 3 | import org.junit.Assert.assertEquals 4 | import org.junit.Test 5 | 6 | /** 7 | * Example local unit test, which will execute on the development machine (host). 8 | * 9 | * See [testing documentation](http://d.android.com/tools/testing). 10 | */ 11 | class ExampleUnitTest { 12 | @Test 13 | fun addition_isCorrect() { 14 | assertEquals(4, 2 + 2) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/custom/aliases/WeatherAppAliases.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.custom.aliases 2 | 3 | import com.arif.kotlincoroutinesplusflow.base.Result 4 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.Forecast 5 | import com.arif.kotlincoroutinesplusflow.room.models.weather.DbWeather 6 | 7 | typealias WeatherResult = Result 8 | 9 | typealias ListOfForecasts = List 10 | 11 | typealias ForecastResults = Result -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/base/Result.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.base 2 | 3 | import com.arif.kotlincoroutinesplusflow.custom.errors.ErrorHandler 4 | 5 | sealed class Result 6 | 7 | class Success(val data: T) : Result() 8 | 9 | class Error( 10 | val exception: Throwable, 11 | val message: String = exception.message ?: ErrorHandler.UNKNOWN_ERROR 12 | ) : Result() 13 | 14 | class Progress(val isLoading: Boolean) : Result() -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/entitymappers/Mapper.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.entitymappers 2 | 3 | import androidx.annotation.WorkerThread 4 | import kotlinx.coroutines.Dispatchers 5 | import kotlinx.coroutines.withContext 6 | 7 | interface Mapper { 8 | 9 | @WorkerThread 10 | suspend fun map(): T { 11 | return withContext(Dispatchers.Default) { 12 | getMapping() 13 | } 14 | } 15 | 16 | @WorkerThread 17 | fun getMapping(): T 18 | } -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #304ffe 4 | #7a7cff 5 | #0026ca 6 | #2962ff 7 | #768fff 8 | #0039cb 9 | #ffffff 10 | #ffffff 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Weather 3 | Show Forecasts 4 | Min temp 5 | Max temp 6 | Sunrise 7 | Sunset 8 | Date 9 | Time 10 | 5 Day forecast for %1$s 11 | Weather 12 | 5 day Forecast for %s 13 | Retry 14 | 15 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/custom/views/IndefiniteSnackbar.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.custom.views 2 | 3 | import android.view.View 4 | import com.arif.kotlincoroutinesplusflow.R 5 | import com.google.android.material.snackbar.Snackbar 6 | 7 | object IndefiniteSnackbar { 8 | 9 | private var snackbar: Snackbar? = null 10 | 11 | fun show(view: View, text: String, action: () -> Unit) { 12 | snackbar = Snackbar.make(view, text, Snackbar.LENGTH_INDEFINITE).apply { 13 | setAction(view.context.getString(R.string.retry)) { action() } 14 | show() 15 | } 16 | } 17 | 18 | fun hide() { 19 | snackbar?.dismiss() 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/home/di/HomeComponent.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.home.di 2 | 3 | import com.arif.kotlincoroutinesplusflow.features.forecasts.ForecastsFragment 4 | import com.arif.kotlincoroutinesplusflow.features.home.HomeActivity 5 | import com.arif.kotlincoroutinesplusflow.features.weather.WeatherFragment 6 | import dagger.Subcomponent 7 | 8 | @HomeScope 9 | @Subcomponent(modules = [HomeViewModelsModule::class]) 10 | interface HomeComponent { 11 | 12 | @Subcomponent.Factory 13 | interface Factory { 14 | fun create(): HomeComponent 15 | } 16 | 17 | fun inject(homeActivity: HomeActivity) 18 | fun inject(weatherFragment: WeatherFragment) 19 | fun inject(forecastsFragment: ForecastsFragment) 20 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/di/components/ApplicationComponent.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.di.components 2 | 3 | import com.arif.kotlincoroutinesplusflow.di.modules.AppModule 4 | import com.arif.kotlincoroutinesplusflow.di.modules.DbModule 5 | import com.arif.kotlincoroutinesplusflow.di.modules.OpenWeatherApiModule 6 | import com.arif.kotlincoroutinesplusflow.di.modules.SubcomponentsModule 7 | import com.arif.kotlincoroutinesplusflow.features.home.di.HomeComponent 8 | import com.squareup.moshi.Moshi 9 | import dagger.Component 10 | import javax.inject.Singleton 11 | 12 | @Component(modules = [AppModule::class, OpenWeatherApiModule::class, DbModule::class, SubcomponentsModule::class]) 13 | @Singleton 14 | interface ApplicationComponent { 15 | fun getMoshi(): Moshi 16 | fun homeComponent(): HomeComponent.Factory 17 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/home/HomeActivity.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.home 2 | 3 | import android.os.Bundle 4 | import androidx.appcompat.app.AppCompatActivity 5 | import com.arif.kotlincoroutinesplusflow.R 6 | import com.arif.kotlincoroutinesplusflow.WeatherApplication 7 | import com.arif.kotlincoroutinesplusflow.features.home.di.HomeComponent 8 | 9 | 10 | class HomeActivity : AppCompatActivity() { 11 | 12 | var homeComponent: HomeComponent? = null 13 | 14 | override fun onCreate(savedInstanceState: Bundle?) { 15 | super.onCreate(savedInstanceState) 16 | setContentView(R.layout.main_activity) 17 | homeComponent = (applicationContext as WeatherApplication) 18 | .appComponent.homeComponent().create() 19 | homeComponent?.inject(this) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/arif/kotlincoroutinesplusflow/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow 2 | 3 | import androidx.test.ext.junit.runners.AndroidJUnit4 4 | import androidx.test.platform.app.InstrumentationRegistry 5 | import org.junit.Assert.assertEquals 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | /** 10 | * Instrumented test, which will execute on an Android device. 11 | * 12 | * See [testing documentation](http://d.android.com/tools/testing). 13 | */ 14 | @RunWith(AndroidJUnit4::class) 15 | class ExampleInstrumentedTest { 16 | @Test 17 | fun useAppContext() { 18 | // Context of the app under test. 19 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 20 | assertEquals("com.arif.kotlincoroutinesplusflow", appContext.packageName) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/custom/views/SpacesItemDecoration.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.custom.views 2 | 3 | import android.graphics.Rect 4 | import android.view.View 5 | import androidx.recyclerview.widget.RecyclerView 6 | 7 | 8 | class SpacesItemDecoration(private val topMargin: Int, private val startMargin: Int) : 9 | RecyclerView.ItemDecoration() { 10 | 11 | override fun getItemOffsets( 12 | outRect: Rect, view: View, 13 | parent: RecyclerView, state: RecyclerView.State 14 | ) { 15 | outRect.apply { 16 | left = startMargin 17 | right = startMargin 18 | bottom = topMargin 19 | top = if (parent.getChildLayoutPosition(view) == 0) { 20 | topMargin 21 | } else { 22 | 0 23 | } 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/di/factories/WeatherViewModelFactory.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.di.factories 2 | 3 | import androidx.lifecycle.ViewModel 4 | import androidx.lifecycle.ViewModelProvider 5 | import dagger.Reusable 6 | import javax.inject.Inject 7 | import javax.inject.Provider 8 | 9 | @Reusable 10 | class WeatherViewModelFactory @Inject constructor( 11 | private val creators: Map, @JvmSuppressWildcards Provider> 12 | ) : ViewModelProvider.Factory { 13 | override fun create(modelClass: Class): T { 14 | val creator = creators[modelClass] ?: creators.entries.firstOrNull { 15 | modelClass.isAssignableFrom(it.key) 16 | }?.value ?: throw IllegalArgumentException("unknown model class $modelClass") 17 | try { 18 | @Suppress("UNCHECKED_CAST") 19 | return creator.get() as T 20 | } catch (e: Exception) { 21 | throw RuntimeException(e) 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/room/dao/utils/StringKeyValueDao.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.room.dao.utils 2 | 3 | import androidx.annotation.NonNull 4 | import androidx.room.Dao 5 | import androidx.room.Insert 6 | import androidx.room.OnConflictStrategy 7 | import androidx.room.Query 8 | import com.arif.kotlincoroutinesplusflow.room.models.utils.StringKeyValuePair 9 | 10 | @Dao 11 | interface StringKeyValueDao { 12 | 13 | @Insert(onConflict = OnConflictStrategy.REPLACE) 14 | suspend fun insert(keyValueData: StringKeyValuePair) 15 | 16 | @Query("SELECT * FROM StringKeyValuePair WHERE `key` = :key LIMIT 1") 17 | suspend fun get(@NonNull key: String): StringKeyValuePair? 18 | 19 | @Query("DELETE FROM StringKeyValuePair WHERE `key` = :key") 20 | suspend fun delete(@NonNull key: String) 21 | 22 | @Query("DELETE FROM StringKeyValuePair") 23 | suspend fun clear() 24 | 25 | @Query("SELECT * FROM StringKeyValuePair") 26 | suspend fun getAll(): List? 27 | 28 | } -------------------------------------------------------------------------------- /app/src/main/res/layout/forecasts_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 14 | 15 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/res/navigation/nav_graph.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 10 | 17 | 18 | 22 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/di/modules/DbModule.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.di.modules 2 | 3 | import android.content.Context 4 | import androidx.room.Room 5 | import com.arif.kotlincoroutinesplusflow.room.db.WeatherDatabase 6 | import com.arif.kotlincoroutinesplusflow.utils.Utils 7 | import dagger.Module 8 | import dagger.Provides 9 | import javax.inject.Singleton 10 | 11 | 12 | @Module 13 | class DbModule { 14 | 15 | @Provides 16 | @Singleton 17 | fun provideWeatherDB(context: Context): WeatherDatabase { 18 | return Room.databaseBuilder(context, WeatherDatabase::class.java, Utils.DATABASE_NAME) 19 | .build() 20 | } 21 | 22 | @Provides 23 | @Singleton 24 | fun provideWeatherDao(weatherDatabase: WeatherDatabase) = 25 | weatherDatabase.weatherDao() 26 | 27 | @Provides 28 | @Singleton 29 | fun provideForecastDao(weatherDatabase: WeatherDatabase) = 30 | weatherDatabase.forecastDao() 31 | 32 | @Provides 33 | @Singleton 34 | fun provideStringKeyValueDao(weatherDatabase: WeatherDatabase) = 35 | weatherDatabase.keyValueDao() 36 | 37 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/network/api/OpenWeatherApi.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.network.api 2 | 3 | import androidx.annotation.WorkerThread 4 | import com.arif.kotlincoroutinesplusflow.network.response.forecast.ApiForecast 5 | import com.arif.kotlincoroutinesplusflow.network.response.weather.ApiWeather 6 | import com.arif.kotlincoroutinesplusflow.utils.Utils 7 | import retrofit2.Response 8 | import retrofit2.http.GET 9 | import retrofit2.http.Query 10 | 11 | interface OpenWeatherApi { 12 | 13 | @WorkerThread 14 | @GET("data/2.5/weather") 15 | suspend fun getWeatherFromCityName( 16 | @Query("q") cityName: String, 17 | @Query("APPID") apiKey: String = Utils.OPEN_WEATHER_MAPS_API_KEY, 18 | @Query("units") units: String = Utils.DEFAULT_UNIT_SYSTEM 19 | ): Response 20 | 21 | @WorkerThread 22 | @GET("data/2.5/forecast") 23 | suspend fun getWeatherForecast( 24 | @Query("id") id: Int, 25 | @Query("APPID") apiKey: String = Utils.OPEN_WEATHER_MAPS_API_KEY, 26 | @Query("units") units: String = Utils.DEFAULT_UNIT_SYSTEM 27 | ): Response 28 | 29 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/home/di/HomeViewModelsModule.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.home.di 2 | 3 | import androidx.lifecycle.ViewModel 4 | import androidx.lifecycle.ViewModelProvider 5 | import com.arif.kotlincoroutinesplusflow.di.ViewModelKey 6 | import com.arif.kotlincoroutinesplusflow.di.factories.WeatherViewModelFactory 7 | import com.arif.kotlincoroutinesplusflow.features.forecasts.ForecastsViewModel 8 | import com.arif.kotlincoroutinesplusflow.features.weather.WeatherViewModel 9 | import dagger.Binds 10 | import dagger.Module 11 | import dagger.multibindings.IntoMap 12 | 13 | @Module 14 | abstract class HomeViewModelsModule { 15 | 16 | @HomeScope 17 | @Binds 18 | @IntoMap 19 | @ViewModelKey(WeatherViewModel::class) 20 | abstract fun bindWeatherViewModel(weatherViewModel: WeatherViewModel): ViewModel 21 | 22 | @HomeScope 23 | @Binds 24 | @IntoMap 25 | @ViewModelKey(ForecastsViewModel::class) 26 | abstract fun bindForecastsViewModel(forecastsViewModel: ForecastsViewModel): ViewModel 27 | 28 | @HomeScope 29 | @Binds 30 | abstract fun bindHomeViewModelFactory(factory: WeatherViewModelFactory): ViewModelProvider.Factory 31 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/room/db/WeatherDatabase.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.room.db 2 | 3 | import androidx.room.Database 4 | import androidx.room.RoomDatabase 5 | import com.arif.kotlincoroutinesplusflow.room.dao.forecasts.ForecastDao 6 | import com.arif.kotlincoroutinesplusflow.room.dao.utils.StringKeyValueDao 7 | import com.arif.kotlincoroutinesplusflow.room.dao.weather.WeatherDao 8 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.Forecast 9 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.ForecastData 10 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.ForecastWeather 11 | import com.arif.kotlincoroutinesplusflow.room.models.utils.StringKeyValuePair 12 | import com.arif.kotlincoroutinesplusflow.room.models.weather.Weather 13 | import com.arif.kotlincoroutinesplusflow.room.models.weather.WeatherData 14 | 15 | @Database( 16 | entities = [WeatherData::class, Weather::class, ForecastData::class, Forecast::class, 17 | ForecastWeather::class, StringKeyValuePair::class], version = 1 18 | ) 19 | abstract class WeatherDatabase : RoomDatabase() { 20 | abstract fun weatherDao(): WeatherDao 21 | abstract fun keyValueDao(): StringKeyValueDao 22 | abstract fun forecastDao(): ForecastDao 23 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/base/BaseFragment.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.base 2 | 3 | import android.view.View 4 | import androidx.fragment.app.Fragment 5 | import com.google.android.material.snackbar.Snackbar 6 | 7 | abstract class BaseFragment : Fragment() { 8 | 9 | fun showSnackBar(view: View, message: String) = 10 | Snackbar.make(view, message, Snackbar.LENGTH_LONG).show() 11 | 12 | /** 13 | * Handle visibility of a View based on the Progress state being passed in 14 | * 15 | * By default View will be shown if Progress is loading, otherwise it will be hidden 16 | * 17 | * Default parameter *reverse* does the opposite, it will hide a View if Progress is loading 18 | * and will show it otherwise. 19 | */ 20 | fun toggleVisibility( 21 | progress: Progress, 22 | shouldHide: Boolean = false, 23 | reverse: Boolean = false 24 | ) = 25 | when (progress.isLoading) { 26 | true -> if (!reverse) View.VISIBLE else { 27 | if (shouldHide) View.INVISIBLE else View.GONE 28 | } 29 | false -> if (!reverse) { 30 | if (shouldHide) View.INVISIBLE else View.GONE 31 | } else View.VISIBLE 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | org.gradle.daemon=true 23 | org.gradle.configureondemand=true 24 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 19 | 21 | 22 | 23 | 24 | 25 | 26 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/WeatherApplication.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow 2 | 3 | import android.app.Application 4 | import com.arif.kotlincoroutinesplusflow.di.components.ApplicationComponent 5 | import com.arif.kotlincoroutinesplusflow.di.components.DaggerApplicationComponent 6 | import com.arif.kotlincoroutinesplusflow.di.modules.AppModule 7 | import com.arif.kotlincoroutinesplusflow.di.modules.DbModule 8 | import com.arif.kotlincoroutinesplusflow.di.modules.OpenWeatherApiModule 9 | import com.squareup.moshi.Moshi 10 | import timber.log.Timber 11 | 12 | class WeatherApplication : Application() { 13 | 14 | lateinit var appComponent: ApplicationComponent 15 | 16 | companion object { 17 | lateinit var moshi: Moshi 18 | } 19 | 20 | override fun onCreate() { 21 | super.onCreate() 22 | if (BuildConfig.DEBUG) { 23 | Timber.plant(Timber.DebugTree()) 24 | } 25 | initDaggerComponent() 26 | moshi = appComponent.getMoshi() 27 | } 28 | 29 | private fun initDaggerComponent() { 30 | appComponent = DaggerApplicationComponent.builder() 31 | .appModule(AppModule(applicationContext)) 32 | .dbModule(DbModule()) 33 | .openWeatherApiModule(OpenWeatherApiModule()) 34 | .build() 35 | } 36 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/room/dao/weather/WeatherDao.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.room.dao.weather 2 | 3 | import androidx.room.* 4 | import com.arif.kotlincoroutinesplusflow.room.models.weather.DbWeather 5 | import com.arif.kotlincoroutinesplusflow.room.models.weather.Weather 6 | import com.arif.kotlincoroutinesplusflow.room.models.weather.WeatherData 7 | import kotlinx.coroutines.flow.Flow 8 | import timber.log.Timber 9 | 10 | @Dao 11 | interface WeatherDao { 12 | 13 | @Insert(onConflict = OnConflictStrategy.REPLACE) 14 | suspend fun insert(dbWeather: WeatherData) 15 | 16 | @Insert(onConflict = OnConflictStrategy.REPLACE) 17 | suspend fun insertList(listWeather: List) 18 | 19 | @Delete 20 | suspend fun delete(dbWeather: WeatherData) 21 | 22 | @Query("DELETE FROM WeatherData") 23 | suspend fun deleteAll() 24 | 25 | @Transaction 26 | suspend fun deleteAllAndInsert(dbWeather: DbWeather) { 27 | Timber.i("DELETING & INSERTING DATA") 28 | deleteAll() 29 | insert(dbWeather.weatherData) 30 | insertList(dbWeather.list) 31 | } 32 | 33 | @Transaction 34 | @Query("SELECT * FROM WeatherData LIMIT 1") 35 | suspend fun get(): DbWeather? 36 | 37 | /** 38 | * Use this to observe DB changes 39 | */ 40 | @Transaction 41 | @Query("SELECT * FROM WeatherData LIMIT 1") 42 | fun getFlow(): Flow 43 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/forecasts/ForecastsViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.forecasts 2 | 3 | import androidx.lifecycle.MutableLiveData 4 | import androidx.lifecycle.ViewModel 5 | import androidx.lifecycle.viewModelScope 6 | import com.arif.kotlincoroutinesplusflow.custom.aliases.ForecastResults 7 | import com.arif.kotlincoroutinesplusflow.extensions.cancelIfActive 8 | import com.arif.kotlincoroutinesplusflow.features.home.di.HomeScope 9 | import com.arif.kotlincoroutinesplusflow.utils.Utils 10 | import kotlinx.coroutines.Job 11 | import kotlinx.coroutines.flow.collect 12 | import kotlinx.coroutines.launch 13 | import javax.inject.Inject 14 | 15 | @HomeScope 16 | class ForecastsViewModel @Inject constructor(private val forecastsRepository: ForecastsRepository) : 17 | ViewModel() { 18 | 19 | private val mutableForecastLiveData = MutableLiveData() 20 | private var getForecastsJob: Job? = null 21 | 22 | val forecastLiveData = mutableForecastLiveData 23 | 24 | /** 25 | * Cancel existing job if running and then launch forecastsRepository.getForecasts using 26 | * viewModelScope 27 | */ 28 | fun getForecasts() { 29 | getForecastsJob.cancelIfActive() 30 | getForecastsJob = viewModelScope.launch { 31 | forecastsRepository.getForecasts(Utils.LONDON_CITY_ID).collect { 32 | mutableForecastLiveData.value = it 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | _Read more about this project [here](https://medium.com/@arifnadeem7/using-coroutines-and-flow-with-mvvm-architecture-796142dbfc2f)_ 2 | 3 | ### Description 4 | This project demonstrates usage of Kotlin coroutines and Flow with MVVM architecture of Android applications. 5 | 6 | ### Libraries used 7 | 8 | 1. [Coroutines](https://kotlinlang.org/docs/reference/coroutines-overview.html) - For offloading long running tasks to background 9 | 10 | 2. [Flow](https://kotlinlang.org/docs/reference/coroutines/flow.html) - Works very well with coroutines, provides us with cold streams which can be transformed using well known reactive operators. 11 | 12 | 3. [Dagger](https://dagger.dev) - For dependency injection 13 | 14 | 4. [Room](https://developer.android.com/training/data-storage/room) - For storing our application data 15 | 16 | 5. [Jetpack Navigation](https://developer.android.com/guide/navigation/navigation-getting-started) - Used to effortlessly navigate between screens. 17 | 18 | 6. [Retrofit](https://github.com/square/retrofit) - For making API calls 19 | 20 | 7. [Material components for Android](https://material.io/develop/android/docs/getting-started/) - For material theming 21 | 22 | ### Acknowledgements: 23 | 24 | * [Video from Android Dev Summit 2019](https://www.youtube.com/watch?v=B8ppnjGPAGE) presented by Jose Alcérreca, Yigit Boyar; which inspired me to develop this project 25 | * Used [Deferred OkHttp initialization](https://www.zacsweers.dev/dagger-party-tricks-deferred-okhttp-init/) as described by Zac Sweers in his blog. 26 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/network/response/weather/ApiWeather.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.network.response.weather 2 | 3 | import com.squareup.moshi.JsonClass 4 | 5 | @JsonClass(generateAdapter = true) 6 | data class ApiWeather( 7 | val coord: Coord, 8 | val weather: List, 9 | val base: String, 10 | val main: Main, 11 | val visibility: Int, 12 | val wind: Wind, 13 | val clouds: Clouds, 14 | val dt: Long, 15 | val sys: Sys, 16 | val id: Int, 17 | val name: String, 18 | val cod: Int 19 | ) 20 | 21 | @JsonClass(generateAdapter = true) 22 | data class Wind( 23 | val speed: Double, 24 | val deg: Double 25 | ) 26 | 27 | @JsonClass(generateAdapter = true) 28 | data class Weather( 29 | val id: Int, 30 | val main: String, 31 | val description: String, 32 | val icon: String 33 | ) 34 | 35 | @JsonClass(generateAdapter = true) 36 | data class Coord( 37 | val lon: Double, 38 | val lat: Double 39 | ) 40 | 41 | @JsonClass(generateAdapter = true) 42 | data class Main( 43 | val temp: Double, 44 | val pressure: Double, 45 | val humidity: Int, 46 | val temp_min: Double, 47 | val temp_max: Double 48 | ) 49 | 50 | @JsonClass(generateAdapter = true) 51 | data class Sys( 52 | val type: Int, 53 | val id: Int, 54 | val message: Double, 55 | val country: String, 56 | val sunrise: Long, 57 | val sunset: Long 58 | ) 59 | 60 | @JsonClass(generateAdapter = true) 61 | data class Clouds( 62 | val all: Int 63 | ) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | *.aab 5 | 6 | # Files for the ART/Dalvik VM 7 | *.dex 8 | 9 | # Java class files 10 | *.class 11 | 12 | # Generated files 13 | bin/ 14 | gen/ 15 | out/ 16 | release/ 17 | 18 | # Gradle files 19 | .gradle/ 20 | build/ 21 | 22 | # Local configuration file (sdk path, etc) 23 | local.properties 24 | 25 | # Proguard folder generated by Eclipse 26 | proguard/ 27 | 28 | # Log Files 29 | *.log 30 | 31 | # Android Studio Navigation editor temp files 32 | .navigation/ 33 | 34 | # Android Studio captures folder 35 | captures/ 36 | 37 | # IntelliJ 38 | *.iml 39 | .idea/ 40 | .idea/workspace.xml 41 | .idea/tasks.xml 42 | .idea/gradle.xml 43 | .idea/assetWizardSettings.xml 44 | .idea/dictionaries 45 | .idea/libraries 46 | # Android Studio 3 in .gitignore file. 47 | .idea/caches 48 | .idea/modules.xml 49 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 50 | .idea/navEditor.xml 51 | 52 | # Keystore files 53 | # Uncomment the following lines if you do not want to check your keystore files in. 54 | #*.jks 55 | #*.keystore 56 | 57 | # External native build folder generated in Android Studio 2.2 and later 58 | .externalNativeBuild 59 | 60 | # Google Services (e.g. APIs or Firebase) 61 | # google-services.json 62 | 63 | # Freeline 64 | freeline.py 65 | freeline/ 66 | freeline_project_description.json 67 | 68 | # fastlane 69 | fastlane/report.xml 70 | fastlane/Preview.html 71 | fastlane/screenshots 72 | fastlane/test_output 73 | fastlane/readme.md 74 | 75 | # Version control 76 | vcs.xml 77 | 78 | # lint 79 | lint/intermediates/ 80 | lint/generated/ 81 | lint/outputs/ 82 | lint/tmp/ 83 | # lint/reports/ 84 | 85 | .DS_Store 86 | .DS_Store? -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | *.aab 5 | 6 | # Files for the ART/Dalvik VM 7 | *.dex 8 | 9 | # Java class files 10 | *.class 11 | 12 | # Generated files 13 | bin/ 14 | gen/ 15 | out/ 16 | # Uncomment the following line in case you need and you don't have the release build type files in your app 17 | # release/ 18 | 19 | # Gradle files 20 | .gradle/ 21 | build/ 22 | 23 | # Local configuration file (sdk path, etc) 24 | local.properties 25 | 26 | # Proguard folder generated by Eclipse 27 | proguard/ 28 | 29 | # Log Files 30 | *.log 31 | 32 | # Android Studio Navigation editor temp files 33 | .navigation/ 34 | 35 | # Android Studio captures folder 36 | captures/ 37 | 38 | # IntelliJ 39 | *.iml 40 | .idea/workspace.xml 41 | .idea/tasks.xml 42 | .idea/gradle.xml 43 | .idea/assetWizardSettings.xml 44 | .idea/dictionaries 45 | .idea/libraries 46 | # Android Studio 3 in .gitignore file. 47 | .idea/caches 48 | .idea/modules.xml 49 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 50 | .idea/navEditor.xml 51 | 52 | # Keystore files 53 | # Uncomment the following lines if you do not want to check your keystore files in. 54 | #*.jks 55 | #*.keystore 56 | 57 | # External native build folder generated in Android Studio 2.2 and later 58 | .externalNativeBuild 59 | 60 | # Google Services (e.g. APIs or Firebase) 61 | # google-services.json 62 | 63 | # Freeline 64 | freeline.py 65 | freeline/ 66 | freeline_project_description.json 67 | 68 | # fastlane 69 | fastlane/report.xml 70 | fastlane/Preview.html 71 | fastlane/screenshots 72 | fastlane/test_output 73 | fastlane/readme.md 74 | 75 | # Version control 76 | vcs.xml 77 | 78 | # lint 79 | lint/intermediates/ 80 | lint/generated/ 81 | lint/outputs/ 82 | lint/tmp/ 83 | lint/reports/ 84 | 85 | .DS_Store 86 | .DS_Store? -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/network/response/forecast/ApiForecast.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.network.response.forecast 2 | 3 | import com.squareup.moshi.JsonClass 4 | 5 | 6 | @JsonClass(generateAdapter = true) 7 | data class ApiForecast( 8 | val cod: String, 9 | val message: Double, 10 | val cnt: Int, 11 | val list: List, 12 | val city: City 13 | ) 14 | 15 | 16 | @JsonClass(generateAdapter = true) 17 | data class City( 18 | val id: Int, 19 | val name: String, 20 | val coord: Coord, 21 | val country: String 22 | ) 23 | 24 | 25 | @JsonClass(generateAdapter = true) 26 | data class Coord( 27 | val lat: Double, 28 | val lon: Double 29 | ) 30 | 31 | 32 | @JsonClass(generateAdapter = true) 33 | data class Forecast( 34 | val dt: Long, 35 | val main: Main, 36 | val weather: List, 37 | val clouds: Clouds, 38 | val wind: Wind, 39 | val sys: Sys, 40 | val dt_txt: String 41 | ) 42 | 43 | 44 | @JsonClass(generateAdapter = true) 45 | data class Weather( 46 | val id: Int, 47 | val main: String, 48 | val description: String, 49 | val icon: String 50 | ) 51 | 52 | 53 | @JsonClass(generateAdapter = true) 54 | data class Sys( 55 | val pod: String 56 | ) 57 | 58 | 59 | @JsonClass(generateAdapter = true) 60 | data class Main( 61 | val temp: Double, 62 | val temp_min: Double, 63 | val temp_max: Double, 64 | val pressure: Double, 65 | val sea_level: Double, 66 | val grnd_level: Double, 67 | val humidity: Double, 68 | val temp_kf: Double 69 | ) 70 | 71 | 72 | @JsonClass(generateAdapter = true) 73 | data class Clouds( 74 | val all: Int 75 | ) 76 | 77 | 78 | @JsonClass(generateAdapter = true) 79 | data class Wind( 80 | val speed: Double, 81 | val deg: Double 82 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/room/models/weather/DbWeather.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.room.models.weather 2 | 3 | import androidx.room.* 4 | 5 | data class DbWeather( 6 | @Embedded 7 | val weatherData: WeatherData, 8 | @Relation(parentColumn = "id", entityColumn = "weatherDataId") 9 | val list: List 10 | ) 11 | 12 | @SuppressWarnings(RoomWarnings.PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED) 13 | @Entity 14 | data class WeatherData( 15 | @Embedded 16 | val coord: Coord, 17 | val base: String, 18 | @Embedded 19 | val main: Main, 20 | val visibility: Int, 21 | @Embedded 22 | val wind: Wind, 23 | @Embedded 24 | val clouds: Clouds, 25 | val dt: Long, 26 | @Embedded 27 | val sys: Sys, 28 | @PrimaryKey 29 | val id: Int, 30 | val name: String, 31 | val cod: Int 32 | ) 33 | 34 | @Entity(primaryKeys = ["speed", "deg"]) 35 | data class Wind( 36 | val speed: Double, 37 | val deg: Double 38 | ) 39 | 40 | @Entity(primaryKeys = ["weatherID"]) 41 | data class Weather( 42 | val weatherID: Int, 43 | val main: String, 44 | val description: String, 45 | val icon: String, 46 | val weatherDataId: Int 47 | ) 48 | 49 | @Entity(primaryKeys = ["lon", "lat"]) 50 | data class Coord( 51 | val lon: Double, 52 | val lat: Double 53 | ) 54 | 55 | @Entity(primaryKeys = ["temp", "pressure", "humidity", "tempMin", "tempMax"]) 56 | data class Main( 57 | val temp: Double, 58 | val pressure: Double, 59 | val humidity: Int, 60 | val tempMin: Double, 61 | val tempMax: Double 62 | ) 63 | 64 | @Entity 65 | data class Sys( 66 | val type: Int, 67 | @PrimaryKey 68 | val sysId: Int, 69 | val message: Double, 70 | val country: String, 71 | val sunrise: Long, 72 | val sunset: Long 73 | ) 74 | 75 | @Entity 76 | data class Clouds( 77 | @PrimaryKey 78 | val all: Int 79 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/room/dao/forecasts/ForecastDao.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.room.dao.forecasts 2 | 3 | import androidx.room.* 4 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.DbForecast 5 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.Forecast 6 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.ForecastData 7 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.ForecastWeather 8 | import timber.log.Timber 9 | 10 | 11 | @Dao 12 | interface ForecastDao { 13 | 14 | @Insert(onConflict = OnConflictStrategy.REPLACE) 15 | suspend fun insert(dbForecast: ForecastData) 16 | 17 | @Insert(onConflict = OnConflictStrategy.REPLACE) 18 | suspend fun insertForecast(list: Forecast) 19 | 20 | @Insert(onConflict = OnConflictStrategy.REPLACE) 21 | suspend fun insertForecastList(list: List) 22 | 23 | @Insert(onConflict = OnConflictStrategy.REPLACE) 24 | suspend fun insertWeatherList(list: List) 25 | 26 | @Delete 27 | suspend fun delete(dbForecast: ForecastData) 28 | 29 | @Query("DELETE FROM ForecastData") 30 | suspend fun deleteAll() 31 | 32 | @Query("DELETE FROM Forecast") 33 | suspend fun deleteAllForecasts() 34 | 35 | @Query("DELETE FROM ForecastWeather") 36 | suspend fun deleteAllForecastWeather() 37 | 38 | @Transaction 39 | suspend fun deleteAllAndInsert(dbForecast: DbForecast) { 40 | Timber.i("DELETING & INSERTING DATA") 41 | deleteAll() 42 | deleteAllForecasts() 43 | deleteAllForecastWeather() 44 | insert(dbForecast.forecastData) 45 | dbForecast.list.forEach { 46 | insertForecast(it.forecast) 47 | insertWeatherList(it.forecastWeather) 48 | } 49 | } 50 | 51 | @Transaction 52 | @Query("SELECT * FROM ForecastData LIMIT 1") 53 | suspend fun get(): DbForecast? 54 | 55 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/entitymappers/weather/WeatherMapper.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.entitymappers.weather 2 | 3 | import androidx.annotation.WorkerThread 4 | import com.arif.kotlincoroutinesplusflow.entitymappers.Mapper 5 | import com.arif.kotlincoroutinesplusflow.network.response.weather.ApiWeather 6 | import com.arif.kotlincoroutinesplusflow.room.models.weather.* 7 | 8 | class WeatherMapper(private val apiWeather: ApiWeather) : Mapper { 9 | 10 | @WorkerThread 11 | override fun getMapping(): DbWeather { 12 | return DbWeather( 13 | WeatherData( 14 | Coord(apiWeather.coord.lon, apiWeather.coord.lat), 15 | apiWeather.base, 16 | Main( 17 | apiWeather.main.temp, 18 | apiWeather.main.pressure, 19 | apiWeather.main.humidity, 20 | apiWeather.main.temp_min, 21 | apiWeather.main.temp_max 22 | ), 23 | apiWeather.visibility, 24 | Wind(apiWeather.wind.speed, apiWeather.wind.deg), 25 | Clouds(apiWeather.clouds.all), 26 | apiWeather.dt, 27 | Sys( 28 | apiWeather.sys.type, 29 | apiWeather.sys.id, 30 | apiWeather.sys.message, 31 | apiWeather.sys.country, 32 | apiWeather.sys.sunrise, 33 | apiWeather.sys.sunset 34 | ), 35 | apiWeather.id, 36 | apiWeather.name, 37 | apiWeather.cod 38 | ), apiWeather.weather.asSequence().map { 39 | (Weather( 40 | it.id, 41 | it.main, 42 | it.description, 43 | it.icon, 44 | apiWeather.id 45 | )) 46 | }.toList() 47 | ) 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/utils/Utils.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.utils 2 | 3 | import com.arif.kotlincoroutinesplusflow.room.models.utils.StringKeyValuePair 4 | import java.text.DecimalFormat 5 | import java.text.SimpleDateFormat 6 | import java.util.* 7 | 8 | object Utils { 9 | const val OPEN_WEATHER_MAPS_API_KEY = "" 10 | const val DEFAULT_UNIT_SYSTEM = "metric" 11 | const val LONDON_CITY = "London" 12 | const val BASE_URL = "http://api.openweathermap.org/" 13 | const val LONDON_CITY_ID = 2643743 14 | const val DATABASE_NAME = "forecastWeather-app" 15 | const val LAST_WEATHER_API_CALL_TIMESTAMP = "last_weather_api_call_timestamp" 16 | const val LAST_FORECASTS_API_CALL_TIMESTAMP = "last_forecasts_api_call_timestamp" 17 | const val MAX_RETRIES = 3L 18 | private const val INITIAL_BACKOFF = 2000L 19 | 20 | private var formatter = SimpleDateFormat("h:mm aa", Locale.getDefault()) 21 | private var dateFormatter = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) 22 | private val df = DecimalFormat("###.#") 23 | 24 | fun getTimeString(timeInMillis: Long): String { 25 | return formatter.format(Date(timeInMillis * 1000)) 26 | } 27 | 28 | fun getDateString(timeInMillis: Long): String { 29 | return dateFormatter.format(Date(timeInMillis * 1000)) 30 | } 31 | 32 | fun getTemperature(temp: Double): String { 33 | return "${df.format(temp)}°C" 34 | } 35 | 36 | fun shouldCallApi( 37 | lastApiCallMillis: String, 38 | cacheThresholdInMillis: Long = 300000L //default value is 5 minutes// 39 | ): Boolean { 40 | return (System.currentTimeMillis() - lastApiCallMillis.toLong()) >= cacheThresholdInMillis 41 | } 42 | 43 | fun getCurrentTimeKeyValuePair(key: String): StringKeyValuePair { 44 | return StringKeyValuePair(key, System.currentTimeMillis().toString()) 45 | } 46 | 47 | fun getBackoffDelay(attempt: Long) = INITIAL_BACKOFF * (attempt + 1) 48 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/di/modules/OpenWeatherApiModule.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.di.modules 2 | 3 | import com.arif.kotlincoroutinesplusflow.BuildConfig 4 | import com.arif.kotlincoroutinesplusflow.extensions.callFactory 5 | import com.arif.kotlincoroutinesplusflow.network.api.OpenWeatherApi 6 | import com.arif.kotlincoroutinesplusflow.utils.Utils 7 | import com.squareup.moshi.Moshi 8 | import dagger.Lazy 9 | import dagger.Module 10 | import dagger.Provides 11 | import okhttp3.OkHttpClient 12 | import okhttp3.logging.HttpLoggingInterceptor 13 | import retrofit2.Retrofit 14 | import retrofit2.converter.moshi.MoshiConverterFactory 15 | import java.util.concurrent.TimeUnit 16 | import javax.inject.Singleton 17 | 18 | @Module 19 | class OpenWeatherApiModule { 20 | 21 | private val timeOut = 20L //20Secs// 22 | 23 | @Provides 24 | @Singleton 25 | fun provideClient(): OkHttpClient { 26 | return OkHttpClient.Builder().apply { 27 | readTimeout(timeOut, TimeUnit.SECONDS) 28 | connectTimeout(timeOut, TimeUnit.SECONDS) 29 | if (BuildConfig.DEBUG) { 30 | HttpLoggingInterceptor().apply { 31 | level = HttpLoggingInterceptor.Level.BODY 32 | addInterceptor(this) 33 | } 34 | } 35 | }.build() 36 | } 37 | 38 | @Provides 39 | @Singleton 40 | fun provideRetrofit(client: Lazy): Retrofit { 41 | return Retrofit.Builder() 42 | .baseUrl(Utils.BASE_URL) 43 | .addConverterFactory(MoshiConverterFactory.create()) 44 | .callFactory { client.get().newCall(it) } 45 | .build() 46 | } 47 | 48 | @Provides 49 | @Singleton 50 | fun provideApi(retrofit: Retrofit): OpenWeatherApi { 51 | return retrofit.create(OpenWeatherApi::class.java) 52 | } 53 | 54 | @Singleton 55 | @Provides 56 | fun provideMoshi(): Moshi { 57 | return Moshi.Builder().build() 58 | } 59 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/forecasts/ForecastsAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.forecasts 2 | 3 | import android.view.LayoutInflater 4 | import android.view.View 5 | import android.view.ViewGroup 6 | import androidx.recyclerview.widget.DiffUtil 7 | import androidx.recyclerview.widget.ListAdapter 8 | import androidx.recyclerview.widget.RecyclerView 9 | import com.arif.kotlincoroutinesplusflow.R 10 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.Forecast 11 | import com.arif.kotlincoroutinesplusflow.utils.Utils 12 | import com.google.android.material.textview.MaterialTextView 13 | 14 | class ForecastsAdapter : ListAdapter(ForecastDiff) { 15 | 16 | private object ForecastDiff : DiffUtil.ItemCallback() { 17 | 18 | override fun areItemsTheSame(oldItem: Forecast, newItem: Forecast) = 19 | oldItem.dt == newItem.dt 20 | 21 | override fun areContentsTheSame(oldItem: Forecast, newItem: Forecast) = oldItem == newItem 22 | } 23 | 24 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ForecastsViewHolder { 25 | return ForecastsViewHolder( 26 | LayoutInflater.from(parent.context) 27 | .inflate(R.layout.forecast_item, parent, false) 28 | ) 29 | } 30 | 31 | override fun onBindViewHolder(holder: ForecastsViewHolder, position: Int) { 32 | holder.bindData(getItem(position)) 33 | } 34 | 35 | class ForecastsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { 36 | private val tvDate: MaterialTextView = itemView.findViewById(R.id.tvDate) 37 | private val tvTime: MaterialTextView = itemView.findViewById(R.id.tvTime) 38 | private val tvMinTemp: MaterialTextView = itemView.findViewById(R.id.tv_min_temp) 39 | private val tvMaxTemp: MaterialTextView = itemView.findViewById(R.id.tv_max_temp) 40 | 41 | fun bindData(forecast: Forecast?) { 42 | forecast?.apply { 43 | tvDate.text = Utils.getDateString(dt) 44 | tvTime.text = Utils.getTimeString(dt) 45 | tvMinTemp.text = Utils.getTemperature(main.tempMin) 46 | tvMaxTemp.text = Utils.getTemperature(main.tempMax) 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/weather/WeatherViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.weather 2 | 3 | import androidx.annotation.MainThread 4 | import androidx.lifecycle.MutableLiveData 5 | import androidx.lifecycle.ViewModel 6 | import androidx.lifecycle.viewModelScope 7 | import com.arif.kotlincoroutinesplusflow.custom.aliases.WeatherResult 8 | import com.arif.kotlincoroutinesplusflow.extensions.cancelIfActive 9 | import com.arif.kotlincoroutinesplusflow.features.home.di.HomeScope 10 | import com.arif.kotlincoroutinesplusflow.utils.Utils 11 | import kotlinx.coroutines.Job 12 | import kotlinx.coroutines.flow.collect 13 | import kotlinx.coroutines.launch 14 | import javax.inject.Inject 15 | 16 | @HomeScope 17 | class WeatherViewModel @Inject constructor(private val weatherRepository: WeatherRepository) : 18 | ViewModel() { 19 | 20 | private val mutableWeatherLiveData = MutableLiveData() 21 | private var getWeatherJob: Job? = null 22 | 23 | //Exposed to View's// 24 | val weatherLiveData = mutableWeatherLiveData 25 | 26 | // Uncomment if you want to observe changes from DB 27 | // private val mutableWeatherData = MutableLiveData() 28 | 29 | // val weatherData = mutableWeatherData 30 | 31 | // init { 32 | // //collect DB changes using the viewModelScope 33 | // viewModelScope.launch { 34 | // weatherRepository.getWeatherDBFlow() 35 | // .collect { mutableWeatherData.value = it } 36 | // } 37 | // } 38 | 39 | /** 40 | * Cancel existing job if running and then launch weatherRepository.getWeather using 41 | * viewModelScope 42 | */ 43 | fun getWeather() { 44 | getWeatherJob.cancelIfActive() 45 | getWeatherJob = viewModelScope.launch { 46 | weatherRepository.getWeather(Utils.LONDON_CITY) 47 | .collect { 48 | mutableWeatherLiveData.value = it 49 | } 50 | } 51 | } 52 | 53 | /** 54 | * Launch from View confining this flow to it's lifecycleScope 55 | */ 56 | @MainThread 57 | suspend fun callWeatherApi() { 58 | weatherRepository.callWeatherApi(Utils.LONDON_CITY) 59 | .collect { 60 | mutableWeatherLiveData.value = it 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/entitymappers/forecasts/ForecastMapper.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.entitymappers.forecasts 2 | 3 | import androidx.annotation.WorkerThread 4 | import com.arif.kotlincoroutinesplusflow.entitymappers.Mapper 5 | import com.arif.kotlincoroutinesplusflow.network.response.forecast.ApiForecast 6 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.* 7 | 8 | class ForecastMapper(private val apiForecast: ApiForecast) : Mapper { 9 | 10 | @WorkerThread 11 | override fun getMapping(): DbForecast { 12 | return DbForecast( 13 | ForecastData( 14 | apiForecast.cod, 15 | apiForecast.message, 16 | apiForecast.cnt, 17 | City( 18 | apiForecast.city.id, 19 | apiForecast.city.name, 20 | Coord(apiForecast.city.coord.lat, apiForecast.city.coord.lon), 21 | apiForecast.city.country 22 | ) 23 | ), 24 | apiForecast.list.asSequence().map { 25 | ForecastAndWeather( 26 | Forecast( 27 | it.dt, 28 | Main( 29 | it.main.temp, 30 | it.main.temp_min, 31 | it.main.temp_max, 32 | it.main.pressure, 33 | it.main.sea_level, 34 | it.main.grnd_level, 35 | it.main.humidity, 36 | it.main.temp_kf 37 | ), 38 | Clouds(it.clouds.all), 39 | Wind(it.wind.speed, it.wind.deg), 40 | Sys(it.sys.pod), 41 | it.dt_txt, 42 | apiForecast.cod 43 | ), it.weather.asSequence().map { weather -> 44 | ForecastWeather( 45 | weather.id, 46 | weather.main, 47 | weather.description, 48 | weather.icon, 49 | it.dt 50 | ) 51 | }.toList() 52 | ) 53 | }.toList() 54 | ) 55 | } 56 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/room/models/forecasts/DbForecast.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.room.models.forecasts 2 | 3 | import androidx.room.Embedded 4 | import androidx.room.Entity 5 | import androidx.room.Relation 6 | 7 | data class DbForecast( 8 | @Embedded 9 | val forecastData: ForecastData, 10 | @Relation(parentColumn = "cod", entityColumn = "forecastDataId", entity = Forecast::class) 11 | val list: List 12 | ) 13 | 14 | @Entity(primaryKeys = ["cod"]) 15 | data class ForecastData( 16 | val cod: String, 17 | val message: Double, 18 | val cnt: Int, 19 | @Embedded 20 | val city: City 21 | ) 22 | 23 | @Entity(primaryKeys = ["cityId"]) 24 | data class City( 25 | val cityId: Int, 26 | val name: String, 27 | @Embedded 28 | val coord: Coord, 29 | val country: String 30 | ) 31 | 32 | @Entity(primaryKeys = ["lat", "lon"]) 33 | data class Coord( 34 | val lat: Double, 35 | val lon: Double 36 | ) 37 | 38 | data class ForecastAndWeather( 39 | @Embedded 40 | val forecast: Forecast, 41 | @Relation(parentColumn = "dt", entityColumn = "forecastId") 42 | val forecastWeather: List 43 | ) 44 | 45 | @Entity(primaryKeys = ["dt"]) 46 | data class Forecast( 47 | val dt: Long, 48 | @Embedded 49 | val main: Main, 50 | @Embedded 51 | val clouds: Clouds, 52 | @Embedded 53 | val wind: Wind, 54 | @Embedded 55 | val sys: Sys, 56 | val dtTxt: String, 57 | val forecastDataId: String 58 | ) 59 | 60 | @Entity(primaryKeys = ["weatherID"]) 61 | data class ForecastWeather( 62 | val weatherID: Int, 63 | val main: String, 64 | val description: String, 65 | val icon: String, 66 | val forecastId: Long 67 | ) 68 | 69 | @Entity(primaryKeys = ["pod"]) 70 | data class Sys( 71 | val pod: String 72 | ) 73 | 74 | @Entity(primaryKeys = ["tempMin", "tempMax"]) 75 | data class Main( 76 | val temp: Double, 77 | val tempMin: Double, 78 | val tempMax: Double, 79 | val pressure: Double, 80 | val seaLevel: Double, 81 | val grndLevel: Double, 82 | val humidity: Double, 83 | val tempKf: Double 84 | ) 85 | 86 | @Entity(primaryKeys = ["all"]) 87 | data class Clouds( 88 | val all: Int 89 | ) 90 | 91 | @Entity(primaryKeys = ["speed", "deg"]) 92 | data class Wind( 93 | val speed: Double, 94 | val deg: Double 95 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/extensions/Extensions.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.extensions 2 | 3 | import com.arif.kotlincoroutinesplusflow.base.Progress 4 | import com.arif.kotlincoroutinesplusflow.base.Result 5 | import com.arif.kotlincoroutinesplusflow.utils.Utils 6 | import kotlinx.coroutines.Job 7 | import kotlinx.coroutines.delay 8 | import kotlinx.coroutines.flow.Flow 9 | import kotlinx.coroutines.flow.onCompletion 10 | import kotlinx.coroutines.flow.onStart 11 | import kotlinx.coroutines.flow.retryWhen 12 | import okhttp3.Call 13 | import okhttp3.OkHttpClient 14 | import okhttp3.Request 15 | import retrofit2.Retrofit 16 | import java.io.IOException 17 | 18 | /** 19 | * A String class extension function which will captitalize 20 | * all first characters of all words in a sentence. 21 | */ 22 | fun String.capitalizeWords(): String = this.split(' ').joinToString(" ") { it.capitalize() } 23 | 24 | @PublishedApi 25 | internal inline fun Retrofit.Builder.callFactory(crossinline body: (Request) -> Call) = 26 | callFactory(object : Call.Factory { 27 | override fun newCall(request: Request): Call = body(request) 28 | }) 29 | 30 | @Suppress("NOTHING_TO_INLINE") 31 | inline fun Retrofit.Builder.delegatingCallFactory(delegate: dagger.Lazy): Retrofit.Builder = 32 | callFactory { 33 | delegate.get().newCall(it) 34 | } 35 | 36 | /** 37 | * You may want to apply some common side-effects to your flow to avoid repeating commonly used 38 | * logic across your app. 39 | * 40 | * For e.g. If you want to show/hide progress then use side-effect methods like 41 | * onStart & onCompletion 42 | * 43 | * You can also write common business logic which is applicable to all flows in your application, 44 | * in this case we are retrying requests 3 times with an exponential delay; if the exception thrown 45 | * is of type IOException. 46 | * 47 | */ 48 | fun Flow>.applyCommonSideEffects() = 49 | retryWhen { cause, attempt -> 50 | when { 51 | (cause is IOException && attempt < Utils.MAX_RETRIES) -> { 52 | delay(Utils.getBackoffDelay(attempt)) 53 | true 54 | } 55 | else -> { 56 | false 57 | } 58 | } 59 | } 60 | .onStart { emit(Progress(isLoading = true)) } 61 | .onCompletion { emit(Progress(isLoading = false)) } 62 | 63 | fun Job?.cancelIfActive() { 64 | if (this?.isActive == true) { 65 | cancel() 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/custom/errors/ErrorHandler.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.custom.errors 2 | 3 | import android.content.Context 4 | import android.view.View 5 | import android.widget.Toast 6 | import com.arif.kotlincoroutinesplusflow.WeatherApplication 7 | import com.arif.kotlincoroutinesplusflow.base.Error 8 | import com.arif.kotlincoroutinesplusflow.custom.views.IndefiniteSnackbar 9 | import com.squareup.moshi.JsonDataException 10 | import okhttp3.ResponseBody 11 | import retrofit2.HttpException 12 | import timber.log.Timber 13 | import java.io.IOException 14 | 15 | object ErrorHandler { 16 | 17 | private const val NETWORK_ERROR_MESSAGE = 18 | "Please check your internet connectivity and try again!" 19 | private const val EMPTY_RESPONSE = "Server returned empty response." 20 | const val NO_SUCH_DATA = "Data not found in the database" 21 | const val UNKNOWN_ERROR = "An unknown error occurred!" 22 | 23 | fun handleError( 24 | view: View, 25 | throwable: Error, 26 | shouldToast: Boolean = false, 27 | shouldShowSnackBar: Boolean = false, 28 | refreshAction: () -> Unit = {} 29 | ) { 30 | if (shouldShowSnackBar) { 31 | showSnackBar(view, message = throwable.message, refresh = refreshAction) 32 | } else { 33 | if (shouldToast) { 34 | showLongToast(view.context, throwable.message) 35 | } 36 | } 37 | when (throwable.exception) { 38 | is IOException -> Timber.e(NETWORK_ERROR_MESSAGE) 39 | is HttpException -> Timber.e( 40 | "HTTP Exception: ${throwable.exception.code()}" 41 | ) 42 | is NoResponseException -> Timber.e(EMPTY_RESPONSE) 43 | is NoDataException -> Timber.e(NO_SUCH_DATA) 44 | else -> Timber.e(throwable.message) 45 | } 46 | } 47 | 48 | private fun showSnackBar(view: View, message: String, refresh: () -> Unit = {}) { 49 | IndefiniteSnackbar.show(view, message, refresh) 50 | } 51 | 52 | private fun showLongToast(context: Context, message: String) = Toast.makeText( 53 | context, 54 | message, 55 | Toast.LENGTH_LONG 56 | ).show() 57 | 58 | inline fun parseError(responseBody: ResponseBody?): T? { 59 | val parser = WeatherApplication.moshi.adapter(T::class.java) 60 | val response = responseBody?.string() 61 | if (response != null) 62 | try { 63 | return parser.fromJson(response) 64 | } catch (e: JsonDataException) { 65 | e.printStackTrace() 66 | } 67 | return null 68 | } 69 | 70 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/forecasts/ForecastsRepository.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.forecasts 2 | 3 | import com.arif.kotlincoroutinesplusflow.base.Error 4 | import com.arif.kotlincoroutinesplusflow.base.Success 5 | import com.arif.kotlincoroutinesplusflow.custom.errors.ErrorHandler 6 | import com.arif.kotlincoroutinesplusflow.custom.errors.NoDataException 7 | import com.arif.kotlincoroutinesplusflow.custom.errors.NoResponseException 8 | import com.arif.kotlincoroutinesplusflow.entitymappers.forecasts.ForecastMapper 9 | import com.arif.kotlincoroutinesplusflow.extensions.applyCommonSideEffects 10 | import com.arif.kotlincoroutinesplusflow.features.home.di.HomeScope 11 | import com.arif.kotlincoroutinesplusflow.network.api.OpenWeatherApi 12 | import com.arif.kotlincoroutinesplusflow.network.response.ErrorResponse 13 | import com.arif.kotlincoroutinesplusflow.room.dao.forecasts.ForecastDao 14 | import com.arif.kotlincoroutinesplusflow.room.dao.utils.StringKeyValueDao 15 | import com.arif.kotlincoroutinesplusflow.room.models.forecasts.DbForecast 16 | import com.arif.kotlincoroutinesplusflow.utils.Utils 17 | import kotlinx.coroutines.Dispatchers 18 | import kotlinx.coroutines.flow.catch 19 | import kotlinx.coroutines.flow.flow 20 | import kotlinx.coroutines.withContext 21 | import javax.inject.Inject 22 | 23 | @HomeScope 24 | class ForecastsRepository @Inject constructor( 25 | private val openWeatherApi: OpenWeatherApi, 26 | private val forecastDao: ForecastDao, 27 | private val stringKeyValueDao: StringKeyValueDao 28 | ) { 29 | 30 | private val forecastCacheThresholdMillis = 3 * 3600000L //3 hours// 31 | 32 | fun getForecasts(cityId: Int) = flow { 33 | stringKeyValueDao.get(Utils.LAST_FORECASTS_API_CALL_TIMESTAMP) 34 | ?.takeIf { !Utils.shouldCallApi(it.value, forecastCacheThresholdMillis) } 35 | ?.let { emit(getDataOrError(NoDataException())) } 36 | ?: emit((getForecastFromAPI(cityId))) 37 | } 38 | .applyCommonSideEffects() 39 | .catch { 40 | emit(getDataOrError(it)) 41 | } 42 | 43 | private suspend fun getForecastFromAPI(cityId: Int) = openWeatherApi.getWeatherForecast(cityId) 44 | .run { 45 | if (isSuccessful && body() != null) { 46 | stringKeyValueDao.insert( 47 | Utils.getCurrentTimeKeyValuePair(Utils.LAST_FORECASTS_API_CALL_TIMESTAMP) 48 | ) 49 | forecastDao.deleteAllAndInsert(ForecastMapper(body()!!).map()) 50 | getDataOrError(NoDataException()) 51 | } else { 52 | Error( 53 | NoResponseException( 54 | ErrorHandler.parseError(errorBody())?.message 55 | ) 56 | ) 57 | } 58 | } 59 | 60 | private suspend fun getDataOrError(throwable: Throwable) = 61 | forecastDao.get() 62 | ?.let { dbValue -> Success(getForecastList(dbValue)) } 63 | ?: Error(throwable) 64 | 65 | private suspend fun getForecastList(dbForecast: DbForecast) = withContext(Dispatchers.Default) { 66 | dbForecast.list.map { it.forecast } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 20 | 21 | 24 | 25 | 30 | 31 | 38 | 39 | 44 | 45 | 50 | 51 | 56 | 57 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | -keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | -renamesourcefileattribute SourceFile 22 | 23 | ### Kotlin Coroutine 24 | # ServiceLoader support 25 | -keepnames class kotlinx.coroutines.internal.MainDispatcherFactory {} 26 | -keepnames class kotlinx.coroutines.CoroutineExceptionHandler {} 27 | -keepnames class kotlinx.coroutines.android.AndroidExceptionPreHandler {} 28 | -keepnames class kotlinx.coroutines.android.AndroidDispatcherFactory {} 29 | 30 | # Most of volatile fields are updated with AFU and should not be mangled 31 | -keepclassmembernames class kotlinx.** { 32 | volatile ; 33 | } 34 | 35 | ### Retrofit 36 | # Retrofit does reflection on generic parameters. InnerClasses is required to use Signature and 37 | # EnclosingMethod is required to use InnerClasses. 38 | -keepattributes Signature, InnerClasses, EnclosingMethod 39 | 40 | # Retrofit does reflection on method and parameter annotations. 41 | -keepattributes RuntimeVisibleAnnotations, RuntimeVisibleParameterAnnotations 42 | 43 | # Retain service method parameters when optimizing. 44 | -keepclassmembers,allowshrinking,allowobfuscation interface * { 45 | @retrofit2.http.* ; 46 | } 47 | 48 | # Ignore annotation used for build tooling. 49 | -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 50 | 51 | # Ignore JSR 305 annotations for embedding nullability information. 52 | -dontwarn javax.annotation.** 53 | 54 | # Guarded by a NoClassDefFoundError try/catch and only used when on the classpath. 55 | -dontwarn kotlin.Unit 56 | 57 | # Top-level functions that can only be used by Kotlin. 58 | -dontwarn retrofit2.KotlinExtensions 59 | -dontwarn retrofit2.KotlinExtensions$* 60 | 61 | # With R8 full mode, it sees no subtypes of Retrofit interfaces since they are created with a Proxy 62 | # and replaces all potential values with null. Explicitly keeping the interfaces prevents this. 63 | -if interface * { @retrofit2.http.* ; } 64 | -keep,allowobfuscation interface <1> 65 | 66 | ### OkHttp3 67 | -dontwarn okhttp3.** 68 | -dontwarn okio.** 69 | -dontwarn javax.annotation.** 70 | # A resource is loaded with a relative path so the package of this class must be preserved. 71 | -keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase 72 | # Animal Sniffer compileOnly dependency to ensure APIs are compatible with older versions of Java. 73 | -dontwarn org.codehaus.mojo.animal_sniffer.* 74 | # OkHttp platform used only on JVM and when Conscrypt dependency is available. 75 | -dontwarn okhttp3.internal.platform.ConscryptPlatform 76 | -dontwarn org.conscrypt.ConscryptHostnameVerifier 77 | 78 | ### Room 79 | -keep class * extends androidx.room.RoomDatabase 80 | -dontwarn androidx.room.paging.** 81 | 82 | ### Project 83 | -keep class com.arif.kotlincoroutinesplusflow.network.response.** { *; } 84 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("com.google.devtools.ksp") version "2.1.21-2.0.1" 3 | } 4 | apply plugin: 'com.android.application' 5 | 6 | apply plugin: 'kotlin-android' 7 | 8 | apply plugin: 'kotlin-parcelize' 9 | 10 | android { 11 | namespace "com.arif.kotlincoroutinesplusflow" 12 | compileSdkVersion 35 13 | buildToolsVersion "34.0.0" 14 | defaultConfig { 15 | applicationId "com.arif.kotlincoroutinesplusflow" 16 | minSdkVersion 21 17 | targetSdkVersion 35 18 | versionCode 1 19 | versionName "1.0" 20 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 21 | javaCompileOptions { 22 | annotationProcessorOptions { 23 | arguments = [ 24 | "room.schemaLocation" : "$projectDir/schemas".toString(), 25 | "room.incremental" : "true", 26 | "room.expandProjection": "true"] 27 | } 28 | } 29 | 30 | } 31 | buildTypes { 32 | release { 33 | shrinkResources true 34 | minifyEnabled true 35 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 36 | } 37 | } 38 | compileOptions { 39 | sourceCompatibility JavaVersion.VERSION_1_8 40 | targetCompatibility JavaVersion.VERSION_1_8 41 | } 42 | buildFeatures { 43 | buildConfig = true 44 | } 45 | } 46 | 47 | tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { 48 | kotlinOptions { 49 | jvmTarget = "1.8" 50 | } 51 | } 52 | 53 | dependencies { 54 | implementation fileTree(dir: 'libs', include: ['*.jar']) 55 | implementation "org.jetbrains.kotlin:kotlin-stdlib:2.1.21" 56 | implementation 'androidx.appcompat:appcompat:1.7.1' 57 | implementation 'androidx.constraintlayout:constraintlayout:2.2.1' 58 | implementation 'androidx.recyclerview:recyclerview:1.4.0' 59 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.9.1" 60 | implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.9.1" 61 | implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.9.1" 62 | implementation "androidx.navigation:navigation-fragment-ktx:2.9.0" 63 | implementation "androidx.navigation:navigation-ui-ktx:2.9.0" 64 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2" 65 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2" 66 | implementation "com.squareup.retrofit2:retrofit:3.0.0" 67 | implementation("com.squareup.okhttp3:logging-interceptor:4.12.0") 68 | implementation "com.squareup.retrofit2:converter-moshi:3.0.0" 69 | implementation("com.squareup.moshi:moshi-kotlin:1.15.2") 70 | ksp("com.squareup.moshi:moshi-kotlin-codegen:1.15.2") 71 | implementation("io.coil-kt.coil3:coil:3.2.0") 72 | implementation("io.coil-kt.coil3:coil-network-okhttp:3.2.0") 73 | implementation "com.google.dagger:dagger:2.56.2" 74 | ksp "com.google.dagger:dagger-compiler:2.56.2" 75 | testImplementation 'junit:junit:4.13.2' 76 | androidTestImplementation 'androidx.test:core-ktx:1.6.1' 77 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' 78 | implementation "androidx.room:room-runtime:2.7.1" 79 | ksp "androidx.room:room-compiler:2.7.1" 80 | implementation "androidx.room:room-ktx:2.7.1" 81 | implementation "com.google.android.material:material:1.12.0" 82 | implementation "androidx.fragment:fragment-ktx:1.8.8" 83 | implementation 'com.jakewharton.timber:timber:5.0.1' 84 | } 85 | -------------------------------------------------------------------------------- /app/src/main/res/values/font_certs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | @array/com_google_android_gms_fonts_certs_dev 5 | @array/com_google_android_gms_fonts_certs_prod 6 | 7 | 8 | 9 | MIIEqDCCA5CgAwIBAgIJANWFuGx90071MA0GCSqGSIb3DQEBBAUAMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTAeFw0wODA0MTUyMzM2NTZaFw0zNTA5MDEyMzM2NTZaMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbTCCASAwDQYJKoZIhvcNAQEBBQADggENADCCAQgCggEBANbOLggKv+IxTdGNs8/TGFy0PTP6DHThvbbR24kT9ixcOd9W+EaBPWW+wPPKQmsHxajtWjmQwWfna8mZuSeJS48LIgAZlKkpFeVyxW0qMBujb8X8ETrWy550NaFtI6t9+u7hZeTfHwqNvacKhp1RbE6dBRGWynwMVX8XW8N1+UjFaq6GCJukT4qmpN2afb8sCjUigq0GuMwYXrFVee74bQgLHWGJwPmvmLHC69EH6kWr22ijx4OKXlSIx2xT1AsSHee70w5iDBiK4aph27yH3TxkXy9V89TDdexAcKk/cVHYNnDBapcavl7y0RiQ4biu8ymM8Ga/nmzhRKya6G0cGw8CAQOjgfwwgfkwHQYDVR0OBBYEFI0cxb6VTEM8YYY6FbBMvAPyT+CyMIHJBgNVHSMEgcEwgb6AFI0cxb6VTEM8YYY6FbBMvAPyT+CyoYGapIGXMIGUMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEQMA4GA1UEChMHQW5kcm9pZDEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDEiMCAGCSqGSIb3DQEJARYTYW5kcm9pZEBhbmRyb2lkLmNvbYIJANWFuGx90071MAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADggEBABnTDPEF+3iSP0wNfdIjIz1AlnrPzgAIHVvXxunW7SBrDhEglQZBbKJEk5kT0mtKoOD1JMrSu1xuTKEBahWRbqHsXclaXjoBADb0kkjVEJu/Lh5hgYZnOjvlba8Ld7HCKePCVePoTJBdI4fvugnL8TsgK05aIskyY0hKI9L8KfqfGTl1lzOv2KoWD0KWwtAWPoGChZxmQ+nBli+gwYMzM1vAkP+aayLe0a1EQimlOalO762r0GXO0ks+UeXde2Z4e+8S/pf7pITEI/tP+MxJTALw9QUWEv9lKTk+jkbqxbsh8nfBUapfKqYn0eidpwq2AzVp3juYl7//fKnaPhJD9gs= 10 | 11 | 12 | 13 | 14 | MIIEQzCCAyugAwIBAgIJAMLgh0ZkSjCNMA0GCSqGSIb3DQEBBAUAMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDAeFw0wODA4MjEyMzEzMzRaFw0zNjAxMDcyMzEzMzRaMHQxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYDVQQKEwtHb29nbGUgSW5jLjEQMA4GA1UECxMHQW5kcm9pZDEQMA4GA1UEAxMHQW5kcm9pZDCCASAwDQYJKoZIhvcNAQEBBQADggENADCCAQgCggEBAKtWLgDYO6IIrgqWbxJOKdoR8qtW0I9Y4sypEwPpt1TTcvZApxsdyxMJZ2JORland2qSGT2y5b+3JKkedxiLDmpHpDsz2WCbdxgxRczfey5YZnTJ4VZbH0xqWVW/8lGmPav5xVwnIiJS6HXk+BVKZF+JcWjAsb/GEuq/eFdpuzSqeYTcfi6idkyugwfYwXFU1+5fZKUaRKYCwkkFQVfcAs1fXA5V+++FGfvjJ/CxURaSxaBvGdGDhfXE28LWuT9ozCl5xw4Yq5OGazvV24mZVSoOO0yZ31j7kYvtwYK6NeADwbSxDdJEqO4k//0zOHKrUiGYXtqw/A0LFFtqoZKFjnkCAQOjgdkwgdYwHQYDVR0OBBYEFMd9jMIhF1Ylmn/Tgt9r45jk14alMIGmBgNVHSMEgZ4wgZuAFMd9jMIhF1Ylmn/Tgt9r45jk14aloXikdjB0MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIGA1UEChMLR29vZ2xlIEluYy4xEDAOBgNVBAsTB0FuZHJvaWQxEDAOBgNVBAMTB0FuZHJvaWSCCQDC4IdGZEowjTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBAUAA4IBAQBt0lLO74UwLDYKqs6Tm8/yzKkEu116FmH4rkaymUIE0P9KaMftGlMexFlaYjzmB2OxZyl6euNXEsQH8gjwyxCUKRJNexBiGcCEyj6z+a1fuHHvkiaai+KL8W1EyNmgjmyy8AW7P+LLlkR+ho5zEHatRbM/YAnqGcFh5iZBqpknHf1SKMXFh4dd239FJ1jWYfbMDMy3NS5CTMQ2XFI1MvcyUTdZPErjQfTbQe3aDQsQcafEQPD+nqActifKZ0Np0IS9L9kR/wbNvyz6ENwPiTrjV2KRkEjH78ZMcUQXg0L3BYHJ3lc69Vs5Ddf9uUGGMYldX3WfMBEmh/9iFBDAaTCK 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/forecasts/ForecastsFragment.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.forecasts 2 | 3 | import android.os.Bundle 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import androidx.core.widget.ContentLoadingProgressBar 8 | import androidx.fragment.app.viewModels 9 | import androidx.lifecycle.Observer 10 | import androidx.lifecycle.ViewModelProvider 11 | import androidx.recyclerview.widget.LinearLayoutManager 12 | import androidx.recyclerview.widget.RecyclerView 13 | import com.arif.kotlincoroutinesplusflow.R 14 | import com.arif.kotlincoroutinesplusflow.base.* 15 | import com.arif.kotlincoroutinesplusflow.custom.aliases.ForecastResults 16 | import com.arif.kotlincoroutinesplusflow.custom.aliases.ListOfForecasts 17 | import com.arif.kotlincoroutinesplusflow.custom.errors.ErrorHandler 18 | import com.arif.kotlincoroutinesplusflow.custom.views.IndefiniteSnackbar 19 | import com.arif.kotlincoroutinesplusflow.custom.views.SpacesItemDecoration 20 | import com.arif.kotlincoroutinesplusflow.features.home.HomeActivity 21 | import com.arif.kotlincoroutinesplusflow.utils.Utils 22 | import javax.inject.Inject 23 | 24 | class ForecastsFragment : BaseFragment() { 25 | 26 | @Inject 27 | lateinit var viewModelFactory: ViewModelProvider.Factory 28 | private val forecastsViewModel: ForecastsViewModel by viewModels { viewModelFactory } 29 | private lateinit var forecastsAdapter: ForecastsAdapter 30 | private lateinit var forecastsRecycler: RecyclerView 31 | private lateinit var pbForecasts: ContentLoadingProgressBar 32 | private val observer = Observer { handleResponse(it) } 33 | 34 | override fun onCreateView( 35 | inflater: LayoutInflater, 36 | container: ViewGroup?, 37 | savedInstanceState: Bundle? 38 | ): View? { 39 | return view ?: inflater.inflate(R.layout.forecasts_fragment, container, false) 40 | } 41 | 42 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 43 | super.onViewCreated(view, savedInstanceState) 44 | initViews(view) 45 | } 46 | 47 | override fun onActivityCreated(savedInstanceState: Bundle?) { 48 | (activity as HomeActivity).title = getString(R.string.forecast, Utils.LONDON_CITY) 49 | (activity as HomeActivity).homeComponent?.inject(this) 50 | forecastsViewModel.forecastLiveData.observe(viewLifecycleOwner, observer) 51 | getForecasts() 52 | super.onActivityCreated(savedInstanceState) 53 | } 54 | 55 | private fun getForecasts() { 56 | IndefiniteSnackbar.hide() 57 | forecastsViewModel.getForecasts() 58 | } 59 | 60 | private fun initViews(view: View) { 61 | forecastsAdapter = ForecastsAdapter() 62 | view.apply { 63 | forecastsRecycler = findViewById(R.id.forecasts_recycler) 64 | pbForecasts = findViewById(R.id.pb_forecasts) 65 | } 66 | forecastsRecycler.apply { 67 | layoutManager = LinearLayoutManager(context) 68 | addItemDecoration( 69 | SpacesItemDecoration( 70 | resources.getDimension(R.dimen.margin_small).toInt(), 71 | resources.getDimension(R.dimen.margin).toInt() 72 | ) 73 | ) 74 | adapter = forecastsAdapter 75 | } 76 | } 77 | 78 | private fun handleResponse(it: Result) { 79 | when (it) { 80 | is Success -> bindData(it.data) 81 | is Error -> view?.let { view -> 82 | ErrorHandler.handleError( 83 | view, 84 | it, 85 | shouldShowSnackBar = true, 86 | refreshAction = { getForecasts() }) 87 | } 88 | is Progress -> { 89 | pbForecasts.visibility = toggleVisibility(it) 90 | } 91 | } 92 | } 93 | 94 | private fun bindData(forecasts: ListOfForecasts) { 95 | forecastsAdapter.submitList(forecasts) 96 | } 97 | } -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/weather/WeatherRepository.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.weather 2 | 3 | import com.arif.kotlincoroutinesplusflow.base.Error 4 | import com.arif.kotlincoroutinesplusflow.base.Success 5 | import com.arif.kotlincoroutinesplusflow.custom.aliases.WeatherResult 6 | import com.arif.kotlincoroutinesplusflow.custom.errors.ErrorHandler 7 | import com.arif.kotlincoroutinesplusflow.custom.errors.NoDataException 8 | import com.arif.kotlincoroutinesplusflow.custom.errors.NoResponseException 9 | import com.arif.kotlincoroutinesplusflow.entitymappers.weather.WeatherMapper 10 | import com.arif.kotlincoroutinesplusflow.extensions.applyCommonSideEffects 11 | import com.arif.kotlincoroutinesplusflow.features.home.di.HomeScope 12 | import com.arif.kotlincoroutinesplusflow.network.api.OpenWeatherApi 13 | import com.arif.kotlincoroutinesplusflow.network.response.ErrorResponse 14 | import com.arif.kotlincoroutinesplusflow.room.dao.utils.StringKeyValueDao 15 | import com.arif.kotlincoroutinesplusflow.room.dao.weather.WeatherDao 16 | import com.arif.kotlincoroutinesplusflow.utils.Utils 17 | import kotlinx.coroutines.flow.catch 18 | import kotlinx.coroutines.flow.flow 19 | import javax.inject.Inject 20 | 21 | @HomeScope 22 | class WeatherRepository @Inject constructor( 23 | private val openWeatherApi: OpenWeatherApi, 24 | private val weatherDao: WeatherDao, 25 | private val stringKeyValueDao: StringKeyValueDao 26 | ) { 27 | 28 | private val weatherCacheThresholdMillis = 3600000L //1 hour// 29 | 30 | fun getWeather(cityName: String) = flow { 31 | stringKeyValueDao.get(Utils.LAST_WEATHER_API_CALL_TIMESTAMP) 32 | ?.takeIf { !Utils.shouldCallApi(it.value, weatherCacheThresholdMillis) } 33 | ?.let { emit(getDataOrError(NoDataException())) } 34 | ?: emit(getWeatherFromAPI(cityName)) 35 | } 36 | .applyCommonSideEffects() 37 | .catch { 38 | emit(getDataOrError(it)) 39 | } 40 | 41 | /** 42 | * Another way... 43 | * 44 | * Use this pattern when your data can change from different places. 45 | * This method calls the API and then saves it's response to the database. 46 | * Caller should also use the function getWeatherDBFlow() to listen for changes and 47 | * update the UI accordingly. 48 | * 49 | * Expected usage 50 | * 51 | * Expose an immutable LiveData from your ViewModel to observe DB changes in your View. 52 | * 53 | * In your ViewModel call this inside init{} block 54 | * 55 | * viewModelScope.launch { 56 | * weatherRepository.getWeatherDBFlow() 57 | * .collect { mutableWeatherData.value = it } 58 | * } 59 | * 60 | * Then call this function callWeatherApi(cityName) from your View's lifecycleScope 61 | * 62 | */ 63 | fun callWeatherApi(cityName: String) = flow { 64 | val lastTimestamp = stringKeyValueDao.get(Utils.LAST_WEATHER_API_CALL_TIMESTAMP) 65 | if (lastTimestamp == null || Utils.shouldCallApi( 66 | lastTimestamp.value, 67 | weatherCacheThresholdMillis 68 | ) 69 | ) { 70 | openWeatherApi.getWeatherFromCityName(cityName) 71 | .run { 72 | if (isSuccessful && body() != null) { 73 | stringKeyValueDao.insert( 74 | Utils.getCurrentTimeKeyValuePair(Utils.LAST_WEATHER_API_CALL_TIMESTAMP) 75 | ) 76 | weatherDao.deleteAllAndInsert(WeatherMapper(body()!!).map()) 77 | } 78 | } 79 | } 80 | }.applyCommonSideEffects().catch { emit(Error(it)) } 81 | 82 | private suspend fun getWeatherFromAPI(cityName: String) = 83 | openWeatherApi.getWeatherFromCityName(cityName) 84 | .run { 85 | if (isSuccessful && body() != null) { 86 | stringKeyValueDao.insert( 87 | Utils.getCurrentTimeKeyValuePair(Utils.LAST_WEATHER_API_CALL_TIMESTAMP) 88 | ) 89 | weatherDao.deleteAllAndInsert(WeatherMapper(body()!!).map()) 90 | getDataOrError(NoDataException()) 91 | } else { 92 | Error( 93 | NoResponseException( 94 | ErrorHandler.parseError(errorBody())?.message 95 | ) 96 | ) 97 | } 98 | } 99 | 100 | private suspend fun getDataOrError(throwable: Throwable) = 101 | weatherDao.get() 102 | ?.let { dbValue -> Success(dbValue) } 103 | ?: Error(throwable) 104 | 105 | //Observe DB changes 106 | fun getWeatherDBFlow() = weatherDao.getFlow() 107 | } -------------------------------------------------------------------------------- /app/src/main/res/layout/forecast_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | 27 | 28 | 39 | 40 | 51 | 52 | 62 | 63 | 64 | 77 | 78 | 88 | 89 | 90 | 101 | 102 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/java/com/arif/kotlincoroutinesplusflow/features/weather/WeatherFragment.kt: -------------------------------------------------------------------------------- 1 | package com.arif.kotlincoroutinesplusflow.features.weather 2 | 3 | import android.os.Bundle 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import android.widget.ImageView 8 | import androidx.core.widget.ContentLoadingProgressBar 9 | import androidx.fragment.app.viewModels 10 | import androidx.lifecycle.Observer 11 | import androidx.lifecycle.ViewModelProvider 12 | import androidx.lifecycle.lifecycleScope 13 | import androidx.navigation.fragment.findNavController 14 | import coil3.load 15 | import com.arif.kotlincoroutinesplusflow.R 16 | import com.arif.kotlincoroutinesplusflow.base.* 17 | import com.arif.kotlincoroutinesplusflow.custom.aliases.WeatherResult 18 | import com.arif.kotlincoroutinesplusflow.custom.errors.ErrorHandler 19 | import com.arif.kotlincoroutinesplusflow.custom.views.IndefiniteSnackbar 20 | import com.arif.kotlincoroutinesplusflow.extensions.capitalizeWords 21 | import com.arif.kotlincoroutinesplusflow.features.home.HomeActivity 22 | import com.arif.kotlincoroutinesplusflow.room.models.weather.DbWeather 23 | import com.arif.kotlincoroutinesplusflow.utils.Utils 24 | import com.google.android.material.button.MaterialButton 25 | import com.google.android.material.card.MaterialCardView 26 | import com.google.android.material.textview.MaterialTextView 27 | import kotlinx.coroutines.launch 28 | import javax.inject.Inject 29 | 30 | class WeatherFragment : BaseFragment() { 31 | 32 | @Inject 33 | lateinit var viewModelFactory: ViewModelProvider.Factory 34 | private val weatherViewModel: WeatherViewModel by viewModels { viewModelFactory } 35 | private lateinit var cvWeather: MaterialCardView 36 | private lateinit var pbHome: ContentLoadingProgressBar 37 | private lateinit var tvCityName: MaterialTextView 38 | private lateinit var tvWeatherName: MaterialTextView 39 | private lateinit var tvWeatherInCelsius: MaterialTextView 40 | private lateinit var weatherIcon: ImageView 41 | private lateinit var tvWeatherDescription: MaterialTextView 42 | private lateinit var tvMinTemp: MaterialTextView 43 | private lateinit var tvMaxTemp: MaterialTextView 44 | private lateinit var tvSunrise: MaterialTextView 45 | private lateinit var tvSunset: MaterialTextView 46 | private lateinit var btnShowForecasts: MaterialButton 47 | private val observer = Observer> { handleResponse(it) } 48 | 49 | //Uncomment if you would instead prefer to listen to data changes from DB 50 | // private val weatherDBObserver = 51 | // Observer { 52 | // it?.let { 53 | // Timber.e("DB DATA CHANGED: ${it.weatherData.id}") 54 | // bindData(it) 55 | // } 56 | // } 57 | 58 | override fun onCreateView( 59 | inflater: LayoutInflater, container: ViewGroup?, 60 | savedInstanceState: Bundle? 61 | ): View { 62 | return view ?: inflater.inflate( 63 | R.layout.weather_fragment, 64 | container, 65 | false 66 | ) 67 | } 68 | 69 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 70 | super.onViewCreated(view, savedInstanceState) 71 | initViews(view) 72 | } 73 | 74 | override fun onActivityCreated(savedInstanceState: Bundle?) { 75 | (activity as HomeActivity).setTitle(R.string.weather) 76 | (activity as HomeActivity).homeComponent?.inject(this) 77 | weatherViewModel.weatherLiveData.observe(viewLifecycleOwner, observer) 78 | //Uncomment if you would instead prefer to listen to data changes from DB 79 | //weatherViewModel.weatherData.observe(viewLifecycleOwner, weatherDBObserver) 80 | getWeather() 81 | super.onActivityCreated(savedInstanceState) 82 | } 83 | 84 | private fun getWeather() { 85 | IndefiniteSnackbar.hide() 86 | weatherViewModel.getWeather() 87 | } 88 | 89 | /** 90 | * Call this method along with weatherViewModel.weatherData.observe if you want to observe 91 | * changes from DB. 92 | */ 93 | private fun callWeatherApi() { 94 | IndefiniteSnackbar.hide() 95 | lifecycleScope.launch { 96 | weatherViewModel.callWeatherApi() 97 | } 98 | } 99 | 100 | private fun handleResponse(result: WeatherResult) { 101 | when (result) { 102 | //comment this Success check if you are observing data from DB 103 | is Success -> bindData(result.data) 104 | is Error -> { 105 | view?.let { view -> 106 | ErrorHandler.handleError( 107 | view, 108 | result, 109 | shouldShowSnackBar = true, 110 | refreshAction = { getWeather() } 111 | ) 112 | } 113 | } 114 | is Progress -> { 115 | pbHome.visibility = toggleVisibility(result) 116 | } 117 | } 118 | } 119 | 120 | private fun initViews(view: View) { 121 | view.apply { 122 | cvWeather = findViewById(R.id.card_view_weather) 123 | pbHome = findViewById(R.id.pb_home) 124 | tvCityName = findViewById(R.id.tv_city_name) 125 | tvWeatherName = findViewById(R.id.tv_weather_name) 126 | tvWeatherInCelsius = findViewById(R.id.tv_weather_celsius) 127 | weatherIcon = findViewById(R.id.weather_icon) 128 | tvWeatherDescription = findViewById(R.id.tv_weather_description) 129 | tvMinTemp = findViewById(R.id.tv_min_temp) 130 | tvMaxTemp = findViewById(R.id.tv_max_temp) 131 | tvSunrise = findViewById(R.id.tv_sunrise) 132 | tvSunset = findViewById(R.id.tv_sunset) 133 | btnShowForecasts = findViewById(R.id.btn_show_forecasts) 134 | } 135 | btnShowForecasts.setOnClickListener { 136 | findNavController().navigate(R.id.action_weatherFragment_to_forecastsFragment) 137 | } 138 | } 139 | 140 | private fun bindData(response: DbWeather) { 141 | with(response) { 142 | tvCityName.text = weatherData.name 143 | tvWeatherInCelsius.text = Utils.getTemperature(weatherData.main.temp) 144 | list.takeIf { it.isNotEmpty() } 145 | ?.get(0) 146 | ?.let { 147 | tvWeatherName.text = it.main 148 | weatherIcon.load("http://openweathermap.org/img/w/${it.icon}.png") 149 | tvWeatherDescription.text = it.description.capitalizeWords() 150 | } 151 | tvMinTemp.text = Utils.getTemperature(weatherData.main.tempMin) 152 | tvMaxTemp.text = Utils.getTemperature(weatherData.main.tempMax) 153 | tvSunrise.text = Utils.getTimeString(weatherData.sys.sunrise) 154 | tvSunset.text = Utils.getTimeString(weatherData.sys.sunset) 155 | } 156 | } 157 | 158 | } 159 | -------------------------------------------------------------------------------- /app/src/main/res/layout/weather_fragment.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 11 | 12 | 19 | 20 | 25 | 26 | 38 | 39 | 51 | 52 | 64 | 65 | 73 | 74 | 87 | 88 | 89 | 99 | 100 | 110 | 111 | 112 | 123 | 124 | 136 | 137 | 138 | 148 | 149 | 161 | 162 | 163 | 174 | 175 | 185 | 186 | 187 | 188 | 189 | 190 | 202 | 203 | 213 | 214 | 215 | 216 | -------------------------------------------------------------------------------- /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 2019 Arif 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 | -------------------------------------------------------------------------------- /app/schemas/com.arif.kotlincoroutinesplusflow.room.db.WeatherDatabase/1.json: -------------------------------------------------------------------------------- 1 | { 2 | "formatVersion": 1, 3 | "database": { 4 | "version": 1, 5 | "identityHash": "275778dc0b0a15a855973354fb27ed98", 6 | "entities": [ 7 | { 8 | "tableName": "WeatherData", 9 | "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`base` TEXT NOT NULL, `visibility` INTEGER NOT NULL, `dt` INTEGER NOT NULL, `id` INTEGER NOT NULL, `name` TEXT NOT NULL, `cod` INTEGER NOT NULL, `lon` REAL NOT NULL, `lat` REAL NOT NULL, `temp` REAL NOT NULL, `pressure` REAL NOT NULL, `humidity` INTEGER NOT NULL, `tempMin` REAL NOT NULL, `tempMax` REAL NOT NULL, `speed` REAL NOT NULL, `deg` REAL NOT NULL, `all` INTEGER NOT NULL, `type` INTEGER NOT NULL, `sysId` INTEGER NOT NULL, `message` REAL NOT NULL, `country` TEXT NOT NULL, `sunrise` INTEGER NOT NULL, `sunset` INTEGER NOT NULL, PRIMARY KEY(`id`))", 10 | "fields": [ 11 | { 12 | "fieldPath": "base", 13 | "columnName": "base", 14 | "affinity": "TEXT", 15 | "notNull": true 16 | }, 17 | { 18 | "fieldPath": "visibility", 19 | "columnName": "visibility", 20 | "affinity": "INTEGER", 21 | "notNull": true 22 | }, 23 | { 24 | "fieldPath": "dt", 25 | "columnName": "dt", 26 | "affinity": "INTEGER", 27 | "notNull": true 28 | }, 29 | { 30 | "fieldPath": "id", 31 | "columnName": "id", 32 | "affinity": "INTEGER", 33 | "notNull": true 34 | }, 35 | { 36 | "fieldPath": "name", 37 | "columnName": "name", 38 | "affinity": "TEXT", 39 | "notNull": true 40 | }, 41 | { 42 | "fieldPath": "cod", 43 | "columnName": "cod", 44 | "affinity": "INTEGER", 45 | "notNull": true 46 | }, 47 | { 48 | "fieldPath": "coord.lon", 49 | "columnName": "lon", 50 | "affinity": "REAL", 51 | "notNull": true 52 | }, 53 | { 54 | "fieldPath": "coord.lat", 55 | "columnName": "lat", 56 | "affinity": "REAL", 57 | "notNull": true 58 | }, 59 | { 60 | "fieldPath": "main.temp", 61 | "columnName": "temp", 62 | "affinity": "REAL", 63 | "notNull": true 64 | }, 65 | { 66 | "fieldPath": "main.pressure", 67 | "columnName": "pressure", 68 | "affinity": "REAL", 69 | "notNull": true 70 | }, 71 | { 72 | "fieldPath": "main.humidity", 73 | "columnName": "humidity", 74 | "affinity": "INTEGER", 75 | "notNull": true 76 | }, 77 | { 78 | "fieldPath": "main.tempMin", 79 | "columnName": "tempMin", 80 | "affinity": "REAL", 81 | "notNull": true 82 | }, 83 | { 84 | "fieldPath": "main.tempMax", 85 | "columnName": "tempMax", 86 | "affinity": "REAL", 87 | "notNull": true 88 | }, 89 | { 90 | "fieldPath": "wind.speed", 91 | "columnName": "speed", 92 | "affinity": "REAL", 93 | "notNull": true 94 | }, 95 | { 96 | "fieldPath": "wind.deg", 97 | "columnName": "deg", 98 | "affinity": "REAL", 99 | "notNull": true 100 | }, 101 | { 102 | "fieldPath": "clouds.all", 103 | "columnName": "all", 104 | "affinity": "INTEGER", 105 | "notNull": true 106 | }, 107 | { 108 | "fieldPath": "sys.type", 109 | "columnName": "type", 110 | "affinity": "INTEGER", 111 | "notNull": true 112 | }, 113 | { 114 | "fieldPath": "sys.sysId", 115 | "columnName": "sysId", 116 | "affinity": "INTEGER", 117 | "notNull": true 118 | }, 119 | { 120 | "fieldPath": "sys.message", 121 | "columnName": "message", 122 | "affinity": "REAL", 123 | "notNull": true 124 | }, 125 | { 126 | "fieldPath": "sys.country", 127 | "columnName": "country", 128 | "affinity": "TEXT", 129 | "notNull": true 130 | }, 131 | { 132 | "fieldPath": "sys.sunrise", 133 | "columnName": "sunrise", 134 | "affinity": "INTEGER", 135 | "notNull": true 136 | }, 137 | { 138 | "fieldPath": "sys.sunset", 139 | "columnName": "sunset", 140 | "affinity": "INTEGER", 141 | "notNull": true 142 | } 143 | ], 144 | "primaryKey": { 145 | "columnNames": [ 146 | "id" 147 | ], 148 | "autoGenerate": false 149 | }, 150 | "indices": [], 151 | "foreignKeys": [] 152 | }, 153 | { 154 | "tableName": "Weather", 155 | "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`weatherID` INTEGER NOT NULL, `main` TEXT NOT NULL, `description` TEXT NOT NULL, `icon` TEXT NOT NULL, `weatherDataId` INTEGER NOT NULL, PRIMARY KEY(`weatherID`))", 156 | "fields": [ 157 | { 158 | "fieldPath": "weatherID", 159 | "columnName": "weatherID", 160 | "affinity": "INTEGER", 161 | "notNull": true 162 | }, 163 | { 164 | "fieldPath": "main", 165 | "columnName": "main", 166 | "affinity": "TEXT", 167 | "notNull": true 168 | }, 169 | { 170 | "fieldPath": "description", 171 | "columnName": "description", 172 | "affinity": "TEXT", 173 | "notNull": true 174 | }, 175 | { 176 | "fieldPath": "icon", 177 | "columnName": "icon", 178 | "affinity": "TEXT", 179 | "notNull": true 180 | }, 181 | { 182 | "fieldPath": "weatherDataId", 183 | "columnName": "weatherDataId", 184 | "affinity": "INTEGER", 185 | "notNull": true 186 | } 187 | ], 188 | "primaryKey": { 189 | "columnNames": [ 190 | "weatherID" 191 | ], 192 | "autoGenerate": false 193 | }, 194 | "indices": [], 195 | "foreignKeys": [] 196 | }, 197 | { 198 | "tableName": "ForecastData", 199 | "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`cod` TEXT NOT NULL, `message` REAL NOT NULL, `cnt` INTEGER NOT NULL, `cityId` INTEGER NOT NULL, `name` TEXT NOT NULL, `country` TEXT NOT NULL, `lat` REAL NOT NULL, `lon` REAL NOT NULL, PRIMARY KEY(`cod`))", 200 | "fields": [ 201 | { 202 | "fieldPath": "cod", 203 | "columnName": "cod", 204 | "affinity": "TEXT", 205 | "notNull": true 206 | }, 207 | { 208 | "fieldPath": "message", 209 | "columnName": "message", 210 | "affinity": "REAL", 211 | "notNull": true 212 | }, 213 | { 214 | "fieldPath": "cnt", 215 | "columnName": "cnt", 216 | "affinity": "INTEGER", 217 | "notNull": true 218 | }, 219 | { 220 | "fieldPath": "city.cityId", 221 | "columnName": "cityId", 222 | "affinity": "INTEGER", 223 | "notNull": true 224 | }, 225 | { 226 | "fieldPath": "city.name", 227 | "columnName": "name", 228 | "affinity": "TEXT", 229 | "notNull": true 230 | }, 231 | { 232 | "fieldPath": "city.country", 233 | "columnName": "country", 234 | "affinity": "TEXT", 235 | "notNull": true 236 | }, 237 | { 238 | "fieldPath": "city.coord.lat", 239 | "columnName": "lat", 240 | "affinity": "REAL", 241 | "notNull": true 242 | }, 243 | { 244 | "fieldPath": "city.coord.lon", 245 | "columnName": "lon", 246 | "affinity": "REAL", 247 | "notNull": true 248 | } 249 | ], 250 | "primaryKey": { 251 | "columnNames": [ 252 | "cod" 253 | ], 254 | "autoGenerate": false 255 | }, 256 | "indices": [], 257 | "foreignKeys": [] 258 | }, 259 | { 260 | "tableName": "Forecast", 261 | "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`dt` INTEGER NOT NULL, `dtTxt` TEXT NOT NULL, `forecastDataId` TEXT NOT NULL, `temp` REAL NOT NULL, `tempMin` REAL NOT NULL, `tempMax` REAL NOT NULL, `pressure` REAL NOT NULL, `seaLevel` REAL NOT NULL, `grndLevel` REAL NOT NULL, `humidity` REAL NOT NULL, `tempKf` REAL NOT NULL, `all` INTEGER NOT NULL, `speed` REAL NOT NULL, `deg` REAL NOT NULL, `pod` TEXT NOT NULL, PRIMARY KEY(`dt`))", 262 | "fields": [ 263 | { 264 | "fieldPath": "dt", 265 | "columnName": "dt", 266 | "affinity": "INTEGER", 267 | "notNull": true 268 | }, 269 | { 270 | "fieldPath": "dtTxt", 271 | "columnName": "dtTxt", 272 | "affinity": "TEXT", 273 | "notNull": true 274 | }, 275 | { 276 | "fieldPath": "forecastDataId", 277 | "columnName": "forecastDataId", 278 | "affinity": "TEXT", 279 | "notNull": true 280 | }, 281 | { 282 | "fieldPath": "main.temp", 283 | "columnName": "temp", 284 | "affinity": "REAL", 285 | "notNull": true 286 | }, 287 | { 288 | "fieldPath": "main.tempMin", 289 | "columnName": "tempMin", 290 | "affinity": "REAL", 291 | "notNull": true 292 | }, 293 | { 294 | "fieldPath": "main.tempMax", 295 | "columnName": "tempMax", 296 | "affinity": "REAL", 297 | "notNull": true 298 | }, 299 | { 300 | "fieldPath": "main.pressure", 301 | "columnName": "pressure", 302 | "affinity": "REAL", 303 | "notNull": true 304 | }, 305 | { 306 | "fieldPath": "main.seaLevel", 307 | "columnName": "seaLevel", 308 | "affinity": "REAL", 309 | "notNull": true 310 | }, 311 | { 312 | "fieldPath": "main.grndLevel", 313 | "columnName": "grndLevel", 314 | "affinity": "REAL", 315 | "notNull": true 316 | }, 317 | { 318 | "fieldPath": "main.humidity", 319 | "columnName": "humidity", 320 | "affinity": "REAL", 321 | "notNull": true 322 | }, 323 | { 324 | "fieldPath": "main.tempKf", 325 | "columnName": "tempKf", 326 | "affinity": "REAL", 327 | "notNull": true 328 | }, 329 | { 330 | "fieldPath": "clouds.all", 331 | "columnName": "all", 332 | "affinity": "INTEGER", 333 | "notNull": true 334 | }, 335 | { 336 | "fieldPath": "wind.speed", 337 | "columnName": "speed", 338 | "affinity": "REAL", 339 | "notNull": true 340 | }, 341 | { 342 | "fieldPath": "wind.deg", 343 | "columnName": "deg", 344 | "affinity": "REAL", 345 | "notNull": true 346 | }, 347 | { 348 | "fieldPath": "sys.pod", 349 | "columnName": "pod", 350 | "affinity": "TEXT", 351 | "notNull": true 352 | } 353 | ], 354 | "primaryKey": { 355 | "columnNames": [ 356 | "dt" 357 | ], 358 | "autoGenerate": false 359 | }, 360 | "indices": [], 361 | "foreignKeys": [] 362 | }, 363 | { 364 | "tableName": "ForecastWeather", 365 | "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`weatherID` INTEGER NOT NULL, `main` TEXT NOT NULL, `description` TEXT NOT NULL, `icon` TEXT NOT NULL, `forecastId` INTEGER NOT NULL, PRIMARY KEY(`weatherID`))", 366 | "fields": [ 367 | { 368 | "fieldPath": "weatherID", 369 | "columnName": "weatherID", 370 | "affinity": "INTEGER", 371 | "notNull": true 372 | }, 373 | { 374 | "fieldPath": "main", 375 | "columnName": "main", 376 | "affinity": "TEXT", 377 | "notNull": true 378 | }, 379 | { 380 | "fieldPath": "description", 381 | "columnName": "description", 382 | "affinity": "TEXT", 383 | "notNull": true 384 | }, 385 | { 386 | "fieldPath": "icon", 387 | "columnName": "icon", 388 | "affinity": "TEXT", 389 | "notNull": true 390 | }, 391 | { 392 | "fieldPath": "forecastId", 393 | "columnName": "forecastId", 394 | "affinity": "INTEGER", 395 | "notNull": true 396 | } 397 | ], 398 | "primaryKey": { 399 | "columnNames": [ 400 | "weatherID" 401 | ], 402 | "autoGenerate": false 403 | }, 404 | "indices": [], 405 | "foreignKeys": [] 406 | }, 407 | { 408 | "tableName": "StringKeyValuePair", 409 | "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`key`))", 410 | "fields": [ 411 | { 412 | "fieldPath": "key", 413 | "columnName": "key", 414 | "affinity": "TEXT", 415 | "notNull": true 416 | }, 417 | { 418 | "fieldPath": "value", 419 | "columnName": "value", 420 | "affinity": "TEXT", 421 | "notNull": true 422 | } 423 | ], 424 | "primaryKey": { 425 | "columnNames": [ 426 | "key" 427 | ], 428 | "autoGenerate": false 429 | }, 430 | "indices": [], 431 | "foreignKeys": [] 432 | } 433 | ], 434 | "views": [], 435 | "setupQueries": [ 436 | "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", 437 | "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '275778dc0b0a15a855973354fb27ed98')" 438 | ] 439 | } 440 | } --------------------------------------------------------------------------------