├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── values
│ │ │ │ ├── themes.xml
│ │ │ │ ├── strings.xml
│ │ │ │ └── colors.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── currency
│ │ │ │ └── currencyconvertermm
│ │ │ │ ├── features
│ │ │ │ └── currencyconverter
│ │ │ │ │ ├── exceptions
│ │ │ │ │ └── NetworkNotAvailableException.kt
│ │ │ │ │ ├── composables
│ │ │ │ │ ├── UICurrencyConverter.kt
│ │ │ │ │ ├── ConvertCurrencyButton.kt
│ │ │ │ │ ├── SelectedCurrencyListItem.kt
│ │ │ │ │ ├── CurrencyList.kt
│ │ │ │ │ ├── common
│ │ │ │ │ │ ├── AmountTextField.kt
│ │ │ │ │ │ └── CurrencyAutoComplete.kt
│ │ │ │ │ ├── RatesGridView.kt
│ │ │ │ │ └── CurrencyConverterForm.kt
│ │ │ │ │ ├── defferable
│ │ │ │ │ └── PeriodicFetchLatestRates.kt
│ │ │ │ │ └── CurrencyConverterVM.kt
│ │ │ │ ├── ui
│ │ │ │ └── theme
│ │ │ │ │ ├── Color.kt
│ │ │ │ │ ├── Shape.kt
│ │ │ │ │ ├── Type.kt
│ │ │ │ │ └── Theme.kt
│ │ │ │ ├── MainActivity.kt
│ │ │ │ ├── di
│ │ │ │ ├── UseCaseModule.kt
│ │ │ │ ├── CurrencyConverterModule.kt
│ │ │ │ └── DataModule.kt
│ │ │ │ ├── CurrencyApp.kt
│ │ │ │ └── NetworkInfoProviderImpl.kt
│ │ └── AndroidManifest.xml
│ ├── androidTest
│ │ └── java
│ │ │ └── com
│ │ │ └── currency
│ │ │ └── currencyconvertermm
│ │ │ ├── FakeNetworkInfoProvider.kt
│ │ │ ├── FakeCurrencyAPI.kt
│ │ │ ├── CurrencyConversionComposeUITests.kt
│ │ │ └── CurrencyVMTest.kt
│ └── test
│ │ └── java
│ │ └── com
│ │ └── currency
│ │ └── currencyconvertermm
│ │ ├── FakeCurrenciesLocalSource.kt
│ │ └── CurrencyVMTest.kt
├── proguard-rules.pro
└── build.gradle
├── data
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── paypay
│ │ │ └── data
│ │ │ ├── network
│ │ │ ├── CurrencyAPI.kt
│ │ │ ├── NetLatestRates.kt
│ │ │ ├── CurrencyAPIImpl.kt
│ │ │ └── NetworkClient.kt
│ │ │ ├── local
│ │ │ ├── entities
│ │ │ │ └── LocalCurrency.kt
│ │ │ ├── CCDatabase.kt
│ │ │ ├── dao
│ │ │ │ └── CurrenciesDao.kt
│ │ │ └── CurrenciesLocalSourceImpl.kt
│ │ │ └── repo
│ │ │ ├── CurrenciesRepository.kt
│ │ │ └── LatestPricesRepository.kt
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── paypay
│ │ │ └── data
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── paypay
│ │ └── data
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── domain
├── .gitignore
├── src
│ └── main
│ │ └── java
│ │ └── com
│ │ └── currency
│ │ └── domain
│ │ ├── NetworkInfoProvider.kt
│ │ ├── models
│ │ └── DMCurrencies.kt
│ │ ├── CurrenciesRepository.kt
│ │ ├── usecase
│ │ ├── UseCaseLoadCurrenciesDataFromNetwork.kt
│ │ ├── UseCaseLoadLatestPricesFromNetwork.kt
│ │ ├── UseCaseFetchCurrencies.kt
│ │ └── UseCaseFetchLatestPrices.kt
│ │ ├── LatestPricesRepository.kt
│ │ ├── CurrencyConverter.kt
│ │ └── CurrenciesLocalSource.kt
└── build.gradle
├── .idea
├── .name
├── .gitignore
├── vcs.xml
├── compiler.xml
├── misc.xml
├── gradle.xml
└── inspectionProfiles
│ └── Project_Default.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── settings.gradle
├── gradle.properties
├── README.md
├── gradlew.bat
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/data/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/data/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/domain/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/.idea/.name:
--------------------------------------------------------------------------------
1 | CurrencyConvertermm
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/oianmol/CurrencyConverter/master/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/data/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/network/CurrencyAPI.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.network
2 |
3 | interface CurrencyAPI {
4 | suspend fun networkFetchCurrencies(): Map
5 | suspend fun networkFetchLatestRates(): NetLatestRates
6 | }
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/NetworkInfoProvider.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain
2 |
3 | import kotlinx.coroutines.flow.Flow
4 |
5 | interface NetworkInfoProvider {
6 | fun listenToChanges(): Flow
7 | fun hasNetwork(): Boolean
8 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/exceptions/NetworkNotAvailableException.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.exceptions
2 |
3 | class NetworkNotAvailableException(message: String) : Throwable(message)
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Jun 17 15:50:47 IST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | CurrencyConverter
3 | Select a Currency
4 | Enter Amount
5 | Convert
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple200 = Color(0xFFBB86FC)
6 | val Purple500 = Color(0xFF6200EE)
7 | val Purple700 = Color(0xFF3700B3)
8 | val Teal200 = Color(0xFF03DAC5)
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/models/DMCurrencies.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain.models
2 |
3 | data class DMCurrency(val currency: String, val name: String)
4 | data class DMLatestRate(val currency: String, val rate: Double,val name:String) {
5 | fun calculatedRate(input: Double) = rate.times(input)
6 | }
7 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/CurrenciesRepository.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain
2 |
3 | import androidx.paging.PagingData
4 | import com.currency.domain.models.DMCurrency
5 | import kotlinx.coroutines.flow.Flow
6 |
7 | interface CurrenciesRepository {
8 | fun fetchCurrencies(searchKey: String?): Flow>
9 | suspend fun preloadCurrencies()
10 | }
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/network/NetLatestRates.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.network
2 |
3 | import kotlinx.serialization.Serializable
4 |
5 | @Serializable
6 | data class NetLatestRates(
7 | val base: String? = null,
8 | val disclaimer: String? = null,
9 | val license: String? = null,
10 | val rates: Map? = null,
11 | val timestamp: Long? = null
12 | )
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/usecase/UseCaseLoadCurrenciesDataFromNetwork.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain.usecase
2 |
3 | import com.currency.domain.CurrenciesRepository
4 |
5 | class UseCaseLoadCurrenciesDataFromNetwork(
6 | private val currencyRepository: CurrenciesRepository
7 | ) {
8 | suspend fun perform() {
9 | currencyRepository.preloadCurrencies()
10 | }
11 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/ui/theme/Shape.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.ui.theme
2 |
3 | import androidx.compose.foundation.shape.RoundedCornerShape
4 | import androidx.compose.material.Shapes
5 | import androidx.compose.ui.unit.dp
6 |
7 | val Shapes = Shapes(
8 | small = RoundedCornerShape(4.dp),
9 | medium = RoundedCornerShape(4.dp),
10 | large = RoundedCornerShape(0.dp)
11 | )
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/LatestPricesRepository.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain
2 |
3 | import androidx.paging.PagingData
4 | import com.currency.domain.models.DMLatestRate
5 | import kotlinx.coroutines.flow.Flow
6 | import java.util.*
7 |
8 | interface LatestPricesRepository {
9 | suspend fun preloadLatestRates(): Date
10 | fun fetchRates(searchKey: String?, input: Double): Flow>
11 | }
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/usecase/UseCaseLoadLatestPricesFromNetwork.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain.usecase
2 |
3 | import com.currency.domain.LatestPricesRepository
4 | import java.util.*
5 |
6 | class UseCaseLoadLatestPricesFromNetwork(private val latestPricesRepository: LatestPricesRepository) {
7 | suspend fun perform(): Date {
8 | return latestPricesRepository.preloadLatestRates()
9 | }
10 | }
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/local/entities/LocalCurrency.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.local.entities
2 |
3 | import androidx.room.ColumnInfo
4 | import androidx.room.Entity
5 | import androidx.room.PrimaryKey
6 |
7 | @Entity(tableName = "currencies")
8 | data class LocalCurrency(
9 | @PrimaryKey val currency: String,
10 | @ColumnInfo(name = "name") val name: String,
11 | @ColumnInfo(name = "rate") val rate: Double? = null
12 | )
--------------------------------------------------------------------------------
/data/src/test/java/com/paypay/data/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | gradlePluginPortal()
4 | google()
5 | mavenCentral()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 | rootProject.name = "CurrencyConvertermm"
16 | include ':app'
17 | include ':domain'
18 | include ':data'
19 |
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/local/CCDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.local
2 |
3 | import androidx.room.Database
4 | import androidx.room.RoomDatabase
5 | import com.mm.data.local.dao.CurrenciesDao
6 | import com.mm.data.local.entities.LocalCurrency
7 |
8 | @Database(
9 | entities = [LocalCurrency::class],
10 | version = 1,
11 | exportSchema = false
12 | )
13 | abstract class CCDatabase : RoomDatabase() {
14 | abstract fun currenciesDao(): CurrenciesDao
15 | }
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/usecase/UseCaseFetchCurrencies.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain.usecase
2 |
3 | import com.currency.domain.CurrenciesRepository
4 | import com.currency.domain.models.DMCurrency
5 | import kotlinx.coroutines.flow.Flow
6 |
7 | class UseCaseFetchCurrencies(private val currenciesRepository: CurrenciesRepository,) {
8 | fun perform(value: String): Flow> {
9 | return currenciesRepository.fetchCurrencies(value)
10 | }
11 | }
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/domain/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("java-library")
3 | id("org.jetbrains.kotlin.jvm")
4 | }
5 |
6 | java {
7 | sourceCompatibility = JavaVersion.VERSION_1_8
8 | targetCompatibility = JavaVersion.VERSION_1_8
9 | }
10 |
11 | dependencies {
12 | api("org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.6.21")
13 | implementation("androidx.paging:paging-common:3.1.1")
14 | api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1")
15 | implementation("androidx.paging:paging-common-ktx:3.1.1")
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/usecase/UseCaseFetchLatestPrices.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain.usecase
2 |
3 | import com.currency.domain.LatestPricesRepository
4 | import com.currency.domain.models.DMLatestRate
5 | import kotlinx.coroutines.flow.Flow
6 |
7 | class UseCaseFetchLatestPrices(private val latestPricesRepository: LatestPricesRepository) {
8 | fun perform(value: String): Flow> {
9 | val input = value.toDoubleOrNull() ?: 0.0
10 | return latestPricesRepository.fetchRates("", input)
11 | }
12 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/CurrencyConverter.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain
2 |
3 | object CurrencyConverter {
4 | const val CURRENCIES_KEY: String = "currenciesLastTime"
5 | const val LATEST_PRICES_KEY: String = "LATEST_PRICES_KEY"
6 |
7 | const val KEY_LATEST_PRICES = "latestPrices"
8 | const val API_URL = "https://openexchangerates.org/api/"
9 | const val ENDPOINT_CURRENCIES = "currencies.json"
10 | const val LATEST_RATES = "latest.json"
11 | const val keyAppId = "app_id"
12 | const val APP_ID =
13 | "9d65efadab1243a5b429dad873f887b1" // provide this through ENV variables/build config fields
14 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/currency/currencyconvertermm/FakeNetworkInfoProvider.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import com.currency.domain.NetworkInfoProvider
4 | import kotlinx.coroutines.flow.Flow
5 | import kotlinx.coroutines.flow.emptyFlow
6 |
7 | class FakeNetworkInfoProvider : NetworkInfoProvider {
8 | var isEnabled = false
9 | fun networkSwitch(enabled:Boolean){
10 | this.isEnabled = enabled
11 | }
12 |
13 | override fun listenToChanges(): Flow {
14 | return emptyFlow()
15 | }
16 |
17 | override fun hasNetwork(): Boolean {
18 | return isEnabled
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/domain/src/main/java/com/currency/domain/CurrenciesLocalSource.kt:
--------------------------------------------------------------------------------
1 | package com.currency.domain
2 |
3 | import com.currency.domain.models.DMCurrency
4 | import com.currency.domain.models.DMLatestRate
5 | import kotlinx.coroutines.flow.Flow
6 | import java.util.*
7 |
8 | interface CurrenciesLocalSource {
9 | fun fetchLocalRates(searchKey: String?, input: Double): Flow>
10 | suspend fun saveLatestRates(rates: Map?)
11 | suspend fun saveCurrenciesLocally(currencies: Map)
12 | fun fetchLocalCurrencies(searchKey: String?): Flow>
13 | suspend fun canFetchCurrencies(): Boolean
14 | suspend fun canFetchLatestRates(): Boolean
15 | suspend fun latestRatesFetchLastTime(): Date?
16 | }
--------------------------------------------------------------------------------
/data/src/androidTest/java/com/paypay/data/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.mm.data.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/data/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
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/currency/currencyconvertermm/FakeCurrencyAPI.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import com.mm.data.network.CurrencyAPI
4 | import com.mm.data.network.NetLatestRates
5 |
6 | class FakeCurrencyAPI : CurrencyAPI {
7 | override suspend fun networkFetchCurrencies(): Map {
8 | return hashMapOf().apply {
9 | put("INR", "Indian Rupee")
10 | put("XYZ", "XYZ currency")
11 | }
12 | }
13 |
14 | override suspend fun networkFetchLatestRates(): NetLatestRates {
15 | return NetLatestRates(
16 | timestamp = System.currentTimeMillis() / 1000,
17 | rates = hashMapOf().apply {
18 | put("INR", 75.0)
19 | put("XYZ", 100.0)
20 | })
21 |
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/composables/UICurrencyConverter.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.composables
2 |
3 | import androidx.compose.foundation.layout.padding
4 | import androidx.compose.material.*
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.ui.Modifier
7 | import androidx.compose.ui.graphics.Color
8 | import androidx.compose.ui.tooling.preview.Preview
9 | import com.currency.currencyconvertermm.features.currencyconverter.CurrencyConverterVM
10 |
11 | @OptIn(ExperimentalMaterialApi::class)
12 | @Composable
13 | fun UICurrencyConverter(viewModel: CurrencyConverterVM) {
14 | Scaffold(topBar = {
15 | TopAppBar(title = {
16 | Text(text = "Currency Converter")
17 | })
18 | }) { innerPadding ->
19 | CurrencyConverterForm(Modifier.padding(innerPadding), viewModel)
20 | }
21 | }
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/network/CurrencyAPIImpl.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.network
2 |
3 | import com.currency.domain.CurrencyConverter
4 | import io.ktor.client.*
5 | import io.ktor.client.call.*
6 | import io.ktor.client.request.*
7 | import javax.inject.Inject
8 |
9 | class CurrencyAPIImpl @Inject constructor(private val httpClient: HttpClient) : CurrencyAPI {
10 | override suspend fun networkFetchCurrencies(): Map {
11 | return httpClient.get(CurrencyConverter.API_URL + CurrencyConverter.ENDPOINT_CURRENCIES)
12 | .body()
13 | }
14 |
15 | override suspend fun networkFetchLatestRates(): NetLatestRates {
16 | val rates =
17 | httpClient.get(CurrencyConverter.API_URL + CurrencyConverter.LATEST_RATES) {
18 | parameter(CurrencyConverter.keyAppId, CurrencyConverter.APP_ID)
19 | }.body()
20 | return rates
21 | }
22 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.ui.theme
2 |
3 | import androidx.compose.material.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | body1 = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp
15 | )
16 | /* Other default text styles to override
17 | button = TextStyle(
18 | fontFamily = FontFamily.Default,
19 | fontWeight = FontWeight.W500,
20 | fontSize = 14.sp
21 | ),
22 | caption = TextStyle(
23 | fontFamily = FontFamily.Default,
24 | fontWeight = FontWeight.Normal,
25 | fontSize = 12.sp
26 | )
27 | */
28 | )
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/local/dao/CurrenciesDao.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.local.dao
2 |
3 | import androidx.paging.PagingSource
4 | import androidx.room.*
5 | import com.mm.data.local.entities.LocalCurrency
6 | import kotlinx.coroutines.flow.Flow
7 |
8 | @Dao
9 | interface CurrenciesDao {
10 |
11 | @Query("SELECT * FROM currencies")
12 | fun getAll(): List
13 |
14 | // The Int type parameter tells Room to use a PositionalDataSource object.
15 | @Query("SELECT * FROM currencies where currency like :key or name like :key ORDER BY name ASC")
16 | fun currenciesByKey(key: String): Flow>
17 |
18 | // The Int type parameter tells Room to use a PositionalDataSource object.
19 | @Query("SELECT * FROM currencies ORDER BY name ASC")
20 | fun currenciesPaginated(): Flow>
21 |
22 | @Insert(onConflict = OnConflictStrategy.IGNORE)
23 | fun insertAll(currencies: List)
24 |
25 | @Query("UPDATE currencies SET rate = :rate where currency = :key")
26 | fun updateCurrencyRates(key: String, rate: Double)
27 |
28 |
29 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/composables/ConvertCurrencyButton.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.composables
2 |
3 | import androidx.compose.foundation.layout.fillMaxWidth
4 | import androidx.compose.foundation.layout.height
5 | import androidx.compose.foundation.layout.padding
6 | import androidx.compose.material.Button
7 | import androidx.compose.material.Text
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.ui.Modifier
10 | import androidx.compose.ui.res.stringResource
11 | import androidx.compose.ui.unit.dp
12 | import com.currency.currencyconvertermm.R
13 | import com.currency.currencyconvertermm.ui.theme.Typography
14 |
15 | @Composable
16 | fun ConvertCurrencyButton(modifier: Modifier, onClick: () -> Unit) {
17 | Button(
18 | onClick = {
19 | onClick()
20 | },
21 | modifier
22 | .fillMaxWidth()
23 | .height(50.dp)
24 | .padding(top = 8.dp),
25 | ) {
26 | Text(
27 | text = stringResource(R.string.convert),
28 | style = Typography.subtitle2
29 | )
30 | }
31 | }
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/network/NetworkClient.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.network
2 |
3 | import android.util.Log
4 | import io.ktor.client.*
5 | import io.ktor.client.engine.android.*
6 | import io.ktor.client.plugins.contentnegotiation.*
7 | import io.ktor.client.plugins.logging.*
8 | import io.ktor.client.plugins.observer.*
9 | import io.ktor.serialization.kotlinx.json.*
10 | import kotlinx.serialization.json.Json
11 |
12 | object NetworkClient {
13 | private const val TIME_OUT = 60_000
14 |
15 | fun buildNetworkClient() = HttpClient(Android) {
16 |
17 | engine {
18 | connectTimeout = TIME_OUT
19 | socketTimeout = TIME_OUT
20 | }
21 |
22 | install(Logging) {
23 | logger = object : Logger {
24 | override fun log(message: String) {
25 | Log.d("Logger Ktor =>", message) // We Can use Timber!
26 | }
27 |
28 | }
29 | level = LogLevel.ALL
30 | }
31 |
32 | install(ContentNegotiation) {
33 | json(Json {
34 | prettyPrint = true
35 | isLenient = true
36 | })
37 | }
38 |
39 | install(ResponseObserver) {
40 | onResponse { response ->
41 | Log.d("HTTP status:", "${response.status.value}") // We Can use Timber!
42 | }
43 | }
44 | }
45 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/defferable/PeriodicFetchLatestRates.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.defferable
2 |
3 | import android.content.Context
4 | import androidx.hilt.work.HiltWorker
5 | import androidx.work.CoroutineWorker
6 | import androidx.work.WorkerParameters
7 | import com.currency.domain.usecase.UseCaseLoadCurrenciesDataFromNetwork
8 | import com.currency.domain.usecase.UseCaseLoadLatestPricesFromNetwork
9 | import dagger.assisted.Assisted
10 | import dagger.assisted.AssistedInject
11 |
12 | @HiltWorker
13 | class PeriodicFetchLatestRates @AssistedInject constructor(
14 | @Assisted appContext: Context,
15 | @Assisted workerParams: WorkerParameters,
16 | private val useCaseFetchLatestPrices: UseCaseLoadLatestPricesFromNetwork,
17 | private val useCaseLoadCurrenciesDataFromNetwork: UseCaseLoadCurrenciesDataFromNetwork
18 | ) :
19 | CoroutineWorker(appContext, workerParams) {
20 | override suspend fun doWork(): Result {
21 | return try {
22 | useCaseLoadCurrenciesDataFromNetwork.perform()
23 | useCaseFetchLatestPrices.perform()
24 | Result.success()
25 | } catch (ex: Exception) {
26 | Result.failure()
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/composables/SelectedCurrencyListItem.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.composables
2 |
3 | import androidx.compose.foundation.clickable
4 | import androidx.compose.material.*
5 | import androidx.compose.material.icons.Icons
6 | import androidx.compose.material.icons.filled.Clear
7 | import androidx.compose.material.icons.filled.Done
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.ui.Modifier
10 |
11 | @OptIn(ExperimentalMaterialApi::class)
12 | @Composable
13 | fun SelectedCurrencyListItem(selectedCurrency: Pair?, key: String, value: String,modifier: Modifier,onClearCurrency:()->Unit) {
14 | ListItem(icon = {
15 | if (selectedCurrency?.first == key) {
16 | Icon(imageVector = Icons.Default.Done, contentDescription = null)
17 | }
18 | }, text = {
19 | Text(text = value)
20 | }, secondaryText = {
21 | Text(text = key)
22 | }, modifier = modifier, trailing = {
23 | selectedCurrency?.let {
24 | IconButton(onClick = {
25 | onClearCurrency()
26 | }) {
27 | Icon(imageVector = Icons.Default.Clear, contentDescription = null)
28 | }
29 | }
30 | })
31 | }
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/repo/CurrenciesRepository.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.repo
2 |
3 | import com.currency.domain.CurrenciesLocalSource
4 | import com.currency.domain.CurrenciesRepository
5 | import com.currency.domain.models.DMCurrency
6 | import com.mm.data.network.CurrencyAPI
7 | import kotlinx.coroutines.flow.Flow
8 | import kotlinx.coroutines.withContext
9 | import javax.inject.Inject
10 | import kotlin.coroutines.CoroutineContext
11 |
12 | class CurrenciesRepositoryImpl @Inject constructor(
13 | private val coroutineContext: CoroutineContext,
14 | private val currencyAPI: CurrencyAPI,
15 | private val currenciesLocalSource: CurrenciesLocalSource
16 | ) : CurrenciesRepository {
17 |
18 | override suspend fun preloadCurrencies() {
19 | withContext(coroutineContext) {
20 | if (currenciesLocalSource.canFetchCurrencies()) {
21 | val currencies = networkFetchCurrencies()
22 | currenciesLocalSource.saveCurrenciesLocally(currencies)
23 | }
24 | }
25 | }
26 |
27 | private suspend fun networkFetchCurrencies(): Map {
28 | return currencyAPI.networkFetchCurrencies()
29 | }
30 |
31 | override fun fetchCurrencies(
32 | searchKey: String?
33 | ): Flow> {
34 | return currenciesLocalSource.fetchLocalCurrencies(searchKey)
35 | }
36 | }
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.ui.theme
2 |
3 | import androidx.compose.foundation.isSystemInDarkTheme
4 | import androidx.compose.material.MaterialTheme
5 | import androidx.compose.material.darkColors
6 | import androidx.compose.material.lightColors
7 | import androidx.compose.runtime.Composable
8 | import androidx.compose.ui.graphics.Color
9 |
10 | private val DarkColorPalette = darkColors(
11 | primary = Color.Black,
12 | primaryVariant = Color.Black,
13 | secondary = Color.Green
14 | )
15 |
16 | private val LightColorPalette = lightColors(
17 | primary = Purple500,
18 | primaryVariant = Purple700,
19 | secondary = Teal200
20 |
21 | /* Other default colors to override
22 | background = Color.White,
23 | surface = Color.White,
24 | onPrimary = Color.White,
25 | onSecondary = Color.Black,
26 | onBackground = Color.Black,
27 | onSurface = Color.Black,
28 | */
29 | )
30 |
31 | @Composable
32 | fun CurrencyConvertermmTheme(
33 | darkTheme: Boolean = isSystemInDarkTheme(),
34 | content: @Composable () -> Unit
35 | ) {
36 | val colors = if (darkTheme) {
37 | DarkColorPalette
38 | } else {
39 | LightColorPalette
40 | }
41 |
42 | MaterialTheme(
43 | colors = colors,
44 | typography = Typography,
45 | shapes = Shapes,
46 | content = content
47 | )
48 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.activity.viewModels
7 | import androidx.compose.foundation.layout.fillMaxSize
8 | import androidx.compose.material.MaterialTheme
9 | import androidx.compose.material.Surface
10 | import androidx.compose.ui.Modifier
11 | import com.currency.currencyconvertermm.features.currencyconverter.CurrencyConverterVM
12 | import com.currency.currencyconvertermm.features.currencyconverter.composables.UICurrencyConverter
13 | import com.currency.currencyconvertermm.ui.theme.CurrencyConvertermmTheme
14 | import dagger.hilt.android.AndroidEntryPoint
15 |
16 | @AndroidEntryPoint
17 | class MainActivity : ComponentActivity() {
18 |
19 | private val viewModel by viewModels()
20 |
21 | override fun onCreate(savedInstanceState: Bundle?) {
22 | super.onCreate(savedInstanceState)
23 | setContent {
24 | CurrencyConvertermmTheme {
25 | // A surface container using the 'background' color from the theme
26 | Surface(
27 | modifier = Modifier.fillMaxSize(),
28 | color = MaterialTheme.colors.background
29 | ) {
30 | UICurrencyConverter(viewModel)
31 | }
32 | }
33 | }
34 | }
35 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/di/UseCaseModule.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.di
2 |
3 | import com.currency.domain.CurrenciesRepository
4 | import com.currency.domain.LatestPricesRepository
5 | import com.currency.domain.usecase.UseCaseFetchCurrencies
6 | import com.currency.domain.usecase.UseCaseFetchLatestPrices
7 | import com.currency.domain.usecase.UseCaseLoadCurrenciesDataFromNetwork
8 | import com.currency.domain.usecase.UseCaseLoadLatestPricesFromNetwork
9 | import dagger.Module
10 | import dagger.Provides
11 | import dagger.hilt.InstallIn
12 | import dagger.hilt.components.SingletonComponent
13 | import javax.inject.Singleton
14 |
15 | @Module
16 | @InstallIn(SingletonComponent::class)
17 | class UseCaseModule {
18 | @Provides
19 | @Singleton
20 | fun provideUseCaseFetchCurrencies(currenciesRepository: CurrenciesRepository) =
21 | UseCaseFetchCurrencies(currenciesRepository)
22 |
23 | @Provides
24 | @Singleton
25 | fun provideUseCaseFetchLatestPrices(latestPricesRepository: LatestPricesRepository) =
26 | UseCaseFetchLatestPrices(latestPricesRepository)
27 |
28 | @Provides
29 | @Singleton
30 | fun provideUseCaseloadLatestPrices(latestPricesRepository: LatestPricesRepository) =
31 | UseCaseLoadLatestPricesFromNetwork(latestPricesRepository)
32 |
33 | @Provides
34 | @Singleton
35 | fun provideUseCaseLoadCurrenciesData(currenciesRepository: CurrenciesRepository) =
36 | UseCaseLoadCurrenciesDataFromNetwork(currenciesRepository)
37 | }
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/repo/LatestPricesRepository.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.repo
2 |
3 | import androidx.paging.PagingData
4 | import com.currency.domain.LatestPricesRepository
5 | import com.currency.domain.models.DMLatestRate
6 | import com.currency.domain.CurrenciesLocalSource
7 | import com.mm.data.network.CurrencyAPI
8 | import kotlinx.coroutines.flow.Flow
9 | import kotlinx.coroutines.withContext
10 | import java.util.*
11 | import javax.inject.Inject
12 | import kotlin.coroutines.CoroutineContext
13 |
14 | class LatestPricesRepositoryImpl @Inject constructor(
15 | private val coroutineContext: CoroutineContext,
16 | private val currencyAPI: CurrencyAPI,
17 | private val currenciesLocalSource: CurrenciesLocalSource
18 | ) : LatestPricesRepository {
19 |
20 | override fun fetchRates(searchKey: String?, input: Double): Flow> {
21 | return currenciesLocalSource.fetchLocalRates(searchKey, input)
22 | }
23 |
24 | override suspend fun preloadLatestRates(): Date {
25 | return withContext(coroutineContext) {
26 | if (currenciesLocalSource.canFetchLatestRates()) {
27 | val rates = currencyAPI.networkFetchLatestRates()
28 | currenciesLocalSource.saveLatestRates(rates.rates)
29 | currenciesLocalSource.latestRatesFetchLastTime()!!
30 | } else {
31 | currenciesLocalSource.latestRatesFetchLastTime()!!
32 | // ð this will never be null if currenciesLocalSource.canFetchLatestRates() is tru
33 | }
34 | }
35 | }
36 |
37 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/di/CurrencyConverterModule.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.di
2 |
3 | import com.currency.currencyconvertermm.NetworkInfoProviderImpl
4 | import com.currency.domain.CurrenciesLocalSource
5 | import com.currency.domain.CurrenciesRepository
6 | import com.currency.domain.LatestPricesRepository
7 | import com.currency.domain.NetworkInfoProvider
8 | import com.mm.data.local.CurrenciesLocalSourceImpl
9 | import com.mm.data.network.CurrencyAPI
10 | import com.mm.data.network.CurrencyAPIImpl
11 | import com.mm.data.repo.CurrenciesRepositoryImpl
12 | import com.mm.data.repo.LatestPricesRepositoryImpl
13 | import dagger.Binds
14 | import dagger.Module
15 | import dagger.hilt.InstallIn
16 | import dagger.hilt.components.SingletonComponent
17 | import javax.inject.Singleton
18 |
19 | @Module
20 | @InstallIn(SingletonComponent::class)
21 | abstract class CurrencyConverterModule {
22 |
23 | @Binds
24 | @Singleton
25 | abstract fun provideCurrenciesLocalSource(currenciesLocalSource: CurrenciesLocalSourceImpl): CurrenciesLocalSource
26 |
27 | @Binds
28 | @Singleton
29 | abstract fun provideCurrencyApi(currencyAPIImpl: CurrencyAPIImpl): CurrencyAPI
30 |
31 | @Binds
32 | @Singleton
33 | abstract fun provideNetworkInfoProviderImpl(networkInfoProvider: NetworkInfoProviderImpl): NetworkInfoProvider
34 |
35 | @Binds
36 | @Singleton
37 | abstract fun provideLatestPricesRepository(latestPricesRepo: LatestPricesRepositoryImpl): LatestPricesRepository
38 |
39 | @Binds
40 | @Singleton
41 | abstract fun provideCurrenciesRepository(latestPricesRepo: CurrenciesRepositoryImpl): CurrenciesRepository
42 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/CurrencyApp.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import android.app.Application
4 | import androidx.hilt.work.HiltWorkerFactory
5 | import androidx.work.*
6 | import com.currency.currencyconvertermm.features.currencyconverter.defferable.PeriodicFetchLatestRates
7 | import com.currency.domain.CurrencyConverter
8 | import dagger.hilt.android.HiltAndroidApp
9 | import java.util.concurrent.TimeUnit
10 | import javax.inject.Inject
11 |
12 | @HiltAndroidApp
13 | class CurrencyApp : Application(), Configuration.Provider {
14 |
15 | @Inject
16 | lateinit var workerFactory: HiltWorkerFactory
17 |
18 | override fun getWorkManagerConfiguration() =
19 | Configuration.Builder()
20 | .setWorkerFactory(workerFactory)
21 | .build()
22 |
23 | override fun onCreate() {
24 | super.onCreate()
25 | scheduleWork()
26 | }
27 |
28 | private fun scheduleWork() {
29 | val constraints = Constraints.Builder()
30 | .setRequiredNetworkType(NetworkType.CONNECTED)
31 | .setRequiresBatteryNotLow(true)
32 | .setRequiresStorageNotLow(true)
33 | .build()
34 | PeriodicWorkRequestBuilder(
35 | 30,
36 | TimeUnit.MINUTES,
37 | ).setConstraints(constraints)
38 | .build().apply {
39 | WorkManager.getInstance(this@CurrencyApp)
40 | .enqueueUniquePeriodicWork(
41 | CurrencyConverter.KEY_LATEST_PRICES,
42 | ExistingPeriodicWorkPolicy.KEEP,
43 | this
44 | )
45 | }
46 | }
47 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/composables/CurrencyList.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.composables
2 |
3 | import androidx.compose.foundation.clickable
4 | import androidx.compose.foundation.layout.fillMaxHeight
5 | import androidx.compose.foundation.layout.fillMaxWidth
6 | import androidx.compose.foundation.layout.height
7 | import androidx.compose.foundation.lazy.LazyColumn
8 | import androidx.compose.foundation.lazy.items
9 | import androidx.compose.material.ExperimentalMaterialApi
10 | import androidx.compose.material.ListItem
11 | import androidx.compose.material.Text
12 | import androidx.compose.runtime.Composable
13 | import androidx.compose.ui.Modifier
14 | import androidx.compose.ui.text.font.FontWeight
15 | import androidx.compose.ui.unit.dp
16 | import androidx.paging.compose.LazyPagingItems
17 | import androidx.paging.compose.items
18 | import com.currency.currencyconvertermm.ui.theme.Typography
19 | import com.currency.domain.models.DMCurrency
20 |
21 | @OptIn(ExperimentalMaterialApi::class)
22 | @Composable
23 | fun CurrencyList(
24 | currencies: List,
25 | onCurrencySelected: (Pair) -> Unit
26 | ) {
27 | LazyColumn(
28 | Modifier
29 | .fillMaxHeight()
30 | .fillMaxWidth()
31 | ) {
32 | items(currencies) { item ->
33 | ListItem(icon = {
34 | Text(text = item.currency, style = Typography.subtitle1.copy(fontWeight = FontWeight.Bold))
35 | }, text = {
36 | Text(text = item.name)
37 | },modifier = Modifier.clickable {
38 | onCurrencySelected(Pair(item.currency, item.name))
39 | })
40 |
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
22 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/di/DataModule.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.di
2 |
3 | import android.content.Context
4 | import android.net.ConnectivityManager
5 | import androidx.datastore.core.DataStore
6 | import androidx.datastore.preferences.core.Preferences
7 | import androidx.datastore.preferences.preferencesDataStore
8 | import androidx.room.Room
9 | import com.mm.data.local.CCDatabase
10 | import com.mm.data.network.NetworkClient
11 | import dagger.Module
12 | import dagger.Provides
13 | import dagger.hilt.InstallIn
14 | import dagger.hilt.android.qualifiers.ApplicationContext
15 | import dagger.hilt.components.SingletonComponent
16 | import io.ktor.client.*
17 | import kotlinx.coroutines.Dispatchers
18 | import javax.inject.Singleton
19 | import kotlin.coroutines.CoroutineContext
20 |
21 | @Module
22 | @InstallIn(SingletonComponent::class)
23 | class DataModule {
24 |
25 |
26 | @Provides
27 | @Singleton
28 | fun provideCoroutineContext(): CoroutineContext = Dispatchers.IO
29 |
30 | @Provides
31 | @Singleton
32 | fun provideNetworkClient(): HttpClient {
33 | return NetworkClient.buildNetworkClient()
34 | }
35 |
36 | @Provides
37 | @Singleton
38 | fun provideConnectivityManager(@ApplicationContext context: Context) =
39 | context.getSystemService(ConnectivityManager::class.java) as ConnectivityManager
40 |
41 | @Provides
42 | @Singleton
43 | fun provideDataStore(@ApplicationContext context: Context) = context.dataStore
44 |
45 |
46 | @Provides
47 | @Singleton
48 | fun provideCCDatabase(@ApplicationContext context: Context) =
49 | Room.databaseBuilder(context, CCDatabase::class.java, "ccdb")
50 | .fallbackToDestructiveMigration() // TODO don't do this in prod
51 | .build()
52 | }
53 |
54 | val Context.dataStore: DataStore by preferencesDataStore(name = "settings")
55 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CurrencyConverter
2 |
3 | ### Status: Implemented the Open Exchange API
4 |
5 | This is a jetpack compose sample app written in Kotlin following clean architecture principles.
6 |
7 | [OpenExchangeAPI](https://openexchangerates.org/)
8 |
9 | With added Tests!
10 |
11 | 1. Unit Tests
12 | 2. ViewModel Tests
13 | 3. Compose UI Tests
14 |
15 | ## 🏗️️ Built with ❤️ using Jetpack Compose 😁
16 |
17 | | What | How |
18 | |---------------- |------------------------------ |
19 | | 🎭 User Interface (Android) | [Jetpack Compose](https://developer.android.com/jetpack/compose) |
20 | | 🏗 Architecture | [Clean](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) |
21 | | 💉 DI (Android) | [Hilt](https://developer.android.com/training/dependency-injection/hilt-android) |
22 | | 🌊 Async | [Coroutines](https://kotlinlang.org/docs/coroutines-overview.html) + [Flow](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/) |
23 | | 🌐 Networking | [Ktor](https://ktor.io/docs/welcome.html) |
24 | | 📄 Parsing | [KotlinX](https://kotlinlang.org/docs/serialization.html) |
25 |
26 |
27 | License
28 | =======
29 | Copyright 2022 Anmol Verma
30 |
31 | Licensed under the Apache License, Version 2.0 (the "License");
32 | you may not use this file except in compliance with the License.
33 | You may obtain a copy of the License at
34 |
35 | http://www.apache.org/licenses/LICENSE-2.0
36 |
37 | Unless required by applicable law or agreed to in writing, software
38 | distributed under the License is distributed on an "AS IS" BASIS,
39 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
40 | See the License for the specific language governing permissions and
41 | limitations under the License.
42 |
43 |
--------------------------------------------------------------------------------
/data/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'org.jetbrains.kotlin.android'
4 | id 'dagger.hilt.android.plugin'
5 | id 'kotlin-kapt'
6 | id 'kotlinx-serialization'
7 | }
8 |
9 | android {
10 | compileSdk 32
11 |
12 | defaultConfig {
13 | minSdk 21
14 | targetSdk 32
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | consumerProguardFiles "consumer-rules.pro"
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | compileOptions {
27 | sourceCompatibility JavaVersion.VERSION_1_8
28 | targetCompatibility JavaVersion.VERSION_1_8
29 | }
30 | kotlinOptions {
31 | jvmTarget = '1.8'
32 | }
33 | }
34 |
35 | dependencies {
36 | implementation project(":domain")
37 |
38 | implementation "com.google.dagger:hilt-android:2.40.5"
39 | kapt "com.google.dagger:hilt-compiler:2.40.5"
40 |
41 | implementation 'io.ktor:ktor-client-android:2.0.1'
42 | implementation 'io.ktor:ktor-client-logging-jvm:2.0.1'
43 | implementation "io.ktor:ktor-serialization-kotlinx-json:2.0.1"
44 | implementation "io.ktor:ktor-client-content-negotiation:2.0.1"
45 |
46 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1")
47 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1")
48 |
49 | implementation("androidx.room:room-runtime:2.4.2")
50 | kapt("androidx.room:room-compiler:2.4.2")
51 | implementation "androidx.room:room-ktx:2.4.2"
52 | implementation("androidx.room:room-paging:2.4.2")
53 | implementation "androidx.datastore:datastore-preferences:1.0.0"
54 |
55 | testImplementation 'junit:junit:4.13.2'
56 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
57 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
58 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/composables/common/AmountTextField.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.composables.common
2 |
3 | import androidx.compose.foundation.layout.fillMaxWidth
4 | import androidx.compose.foundation.text.KeyboardOptions
5 | import androidx.compose.material.Text
6 | import androidx.compose.material.TextField
7 | import androidx.compose.runtime.Composable
8 | import androidx.compose.ui.Modifier
9 | import androidx.compose.ui.res.stringResource
10 | import androidx.compose.ui.text.input.KeyboardType
11 | import androidx.compose.ui.text.style.TextAlign
12 | import com.currency.currencyconvertermm.R
13 |
14 | @Composable
15 | fun CurrencyTextField(
16 | fieldValue: String,
17 | onChange: (String) -> Unit,
18 | modifier: Modifier = Modifier
19 | ) {
20 | TextField(
21 | value = fieldValue,
22 | onValueChange = { newValue ->
23 | onChange(getValidatedNumber(newValue))
24 | },
25 | leadingIcon = {
26 | Text(text = "$")
27 | },
28 | trailingIcon = {
29 | Text(
30 | text = "",
31 | )
32 | },
33 | placeholder = {
34 | Text(
35 | text = stringResource(R.string.enter_amount),
36 | textAlign = TextAlign.Start,
37 | modifier = Modifier.fillMaxWidth()
38 | )
39 | },
40 | singleLine = true,
41 | maxLines = 1,
42 | modifier = modifier, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
43 | )
44 | }
45 |
46 |
47 | fun getValidatedNumber(text: String): String {
48 | // Start by filtering out unwanted characters like commas and multiple decimals
49 | val filteredChars = text.filterIndexed { index, c ->
50 | c in "0123456789" || // Take all digits
51 | (c == '.' && text.indexOf('.') == index) // Take only the first decimal
52 | }
53 | return filteredChars
54 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/NetworkInfoProviderImpl.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import android.net.ConnectivityManager
4 | import android.net.Network
5 | import android.net.NetworkCapabilities
6 | import android.net.NetworkRequest
7 | import com.currency.domain.NetworkInfoProvider
8 | import kotlinx.coroutines.channels.awaitClose
9 | import kotlinx.coroutines.flow.Flow
10 | import kotlinx.coroutines.flow.callbackFlow
11 | import javax.inject.Inject
12 |
13 | class NetworkInfoProviderImpl @Inject constructor(private val connectivityManager: ConnectivityManager) :
14 | NetworkInfoProvider {
15 |
16 | override fun hasNetwork(): Boolean {
17 | val caps = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
18 | return caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
19 | }
20 |
21 | override fun listenToChanges(): Flow {
22 | return callbackFlow {
23 | val networkCallback = object : ConnectivityManager.NetworkCallback() {
24 | // network is available for use
25 | override fun onAvailable(network: Network) {
26 | super.onAvailable(network)
27 | this@callbackFlow.trySend(true)
28 | }
29 |
30 | // lost network connection
31 | override fun onLost(network: Network) {
32 | super.onLost(network)
33 | this@callbackFlow.trySend(false)
34 | }
35 | }
36 | connectivityManager.requestNetwork(
37 | NetworkRequest.Builder()
38 | .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
39 | .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
40 | .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
41 | .build(), networkCallback
42 | )
43 | this.awaitClose {
44 | connectivityManager.unregisterNetworkCallback(networkCallback)
45 | }
46 | }
47 |
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/composables/common/CurrencyAutoComplete.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.composables.common
2 |
3 | import androidx.compose.foundation.layout.fillMaxWidth
4 | import androidx.compose.foundation.text.KeyboardActions
5 | import androidx.compose.foundation.text.KeyboardOptions
6 | import androidx.compose.material.*
7 | import androidx.compose.material.icons.Icons
8 | import androidx.compose.material.icons.filled.Close
9 | import androidx.compose.runtime.*
10 | import androidx.compose.ui.Modifier
11 | import androidx.compose.ui.focus.onFocusChanged
12 | import androidx.compose.ui.text.input.ImeAction
13 | import androidx.compose.ui.text.input.KeyboardType
14 |
15 | @Composable
16 | fun CurrencyAutoComplete(
17 | modifier: Modifier = Modifier,
18 | query: String,
19 | label: String,
20 | isReadOnly:Boolean,
21 | onDoneActionClick: () -> Unit = {},
22 | onClearClick: () -> Unit = {},
23 | onQueryChanged: (String) -> Unit
24 | ) {
25 | var showClearButton by remember { mutableStateOf(false) }
26 |
27 | LaunchedEffect(key1 = isReadOnly, block = {
28 | showClearButton = !isReadOnly
29 | })
30 |
31 | TextField(
32 | modifier = modifier
33 | .fillMaxWidth()
34 | .onFocusChanged { focusState ->
35 | showClearButton = (focusState.isFocused)
36 | },
37 | value = query,
38 | onValueChange = onQueryChanged,
39 | placeholder = { Text(text = label) },
40 | textStyle = MaterialTheme.typography.subtitle1,
41 | singleLine = true,
42 | trailingIcon = {
43 | if (showClearButton) {
44 | IconButton(onClick = { onClearClick() }) {
45 | Icon(imageVector = Icons.Filled.Close, contentDescription = "Clear")
46 | }
47 | }
48 |
49 | },
50 | keyboardActions = KeyboardActions(onDone = {
51 | onDoneActionClick()
52 | }),
53 | keyboardOptions = KeyboardOptions(
54 | imeAction = ImeAction.Done,
55 | keyboardType = KeyboardType.Text
56 | ), readOnly = isReadOnly
57 | )
58 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/composables/RatesGridView.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.composables
2 |
3 | import androidx.compose.foundation.layout.padding
4 | import androidx.compose.foundation.lazy.LazyColumn
5 | import androidx.compose.foundation.lazy.items
6 | import androidx.compose.material.ExperimentalMaterialApi
7 | import androidx.compose.material.ListItem
8 | import androidx.compose.material.Text
9 | import androidx.compose.runtime.Composable
10 | import androidx.compose.runtime.collectAsState
11 | import androidx.compose.runtime.getValue
12 | import androidx.compose.ui.Modifier
13 | import androidx.compose.ui.text.font.FontWeight
14 | import androidx.compose.ui.unit.dp
15 | import androidx.paging.compose.collectAsLazyPagingItems
16 | import com.currency.currencyconvertermm.features.currencyconverter.CurrencyConverterVM
17 | import com.currency.currencyconvertermm.ui.theme.Typography
18 | import com.currency.domain.models.DMLatestRate
19 |
20 | @Composable
21 | fun RatesView(viewModel: CurrencyConverterVM) {
22 | val ratesFlow by viewModel.latestRatesState.collectAsState()
23 | val rates by ratesFlow.collectAsState(initial = emptyList())
24 | val amount by viewModel.amountForConversion.collectAsState()
25 | LazyColumn(content = {
26 | items(rates) { rate ->
27 | RateView(rate, amount)
28 | }
29 | })
30 | }
31 |
32 | @OptIn(ExperimentalMaterialApi::class)
33 | @Composable
34 | fun RateView(dmLatestRate: DMLatestRate?, amount: String) {
35 | dmLatestRate?.let {
36 | ListItem(text = {
37 | Text(
38 | text = "Rate: " + it.rate.toString(),
39 | style = Typography.subtitle2.copy(fontWeight = FontWeight.Normal),
40 | modifier = Modifier.padding(4.dp)
41 | )
42 | }, secondaryText = {
43 | Text(
44 | text = "Converted: ${it.name} to " + it.calculatedRate(amount.toDoubleOrNull() ?: 0.0).toString(),
45 | style = Typography.subtitle2.copy(fontWeight = FontWeight.Normal),
46 | modifier = Modifier.padding(4.dp)
47 | )
48 |
49 | }, trailing = {
50 | Text(
51 | text = it.currency,
52 | style = Typography.subtitle1.copy(fontWeight = FontWeight.Bold),
53 | modifier = Modifier.padding(4.dp)
54 | )
55 | })
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/app/src/test/java/com/currency/currencyconvertermm/FakeCurrenciesLocalSource.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import com.currency.domain.CurrenciesLocalSource
4 | import com.currency.domain.models.DMCurrency
5 | import com.currency.domain.models.DMLatestRate
6 | import kotlinx.coroutines.flow.Flow
7 | import kotlinx.coroutines.flow.flowOf
8 | import java.util.*
9 |
10 |
11 | data class FakeCurrencyTable(
12 | var currency: String,
13 | var rate: Double,
14 | val calculatedRate: Double? = null,
15 | val name: String
16 | )
17 |
18 | class FakeCurrenciesLocalSource : CurrenciesLocalSource {
19 |
20 | private val currenciesFakeTable = hashSetOf()
21 |
22 | override fun fetchLocalRates(
23 | searchKey: String?,
24 | input: Double
25 | ): Flow> {
26 | return flowOf(currenciesFakeTable.map {
27 | DMLatestRate(
28 | currency = it.currency,
29 | rate = it.rate, name = it.name
30 | )
31 | })
32 | }
33 |
34 | override suspend fun saveLatestRates(rates: Map?) {
35 | currenciesFakeTable.forEach { fake ->
36 | rates?.entries?.forEach {
37 | if (it.key == fake.currency) {
38 | fake.rate = it.value
39 | fake.currency = it.key
40 | }
41 | }
42 | }
43 | }
44 |
45 | override suspend fun saveCurrenciesLocally(currencies: Map) {
46 | currencies.entries.forEach { (key, value) ->
47 | currenciesFakeTable.add(
48 | FakeCurrencyTable(
49 | currency = key,
50 | rate = 0.0,
51 | calculatedRate = 0.0,
52 | name = value
53 | )
54 | )
55 | }
56 | }
57 |
58 | override fun fetchLocalCurrencies(searchKey: String?): Flow> {
59 | return flowOf(currenciesFakeTable.map {
60 | DMCurrency(
61 | currency = it.currency,
62 | name = it.name
63 | )
64 | })
65 | }
66 |
67 | override suspend fun canFetchCurrencies(): Boolean {
68 | return true
69 | }
70 |
71 | override suspend fun canFetchLatestRates(): Boolean {
72 | return true
73 | }
74 |
75 | override suspend fun latestRatesFetchLastTime(): Date? {
76 | return Date()
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'org.jetbrains.kotlin.android'
4 | id 'kotlin-kapt'
5 | id 'dagger.hilt.android.plugin'
6 | id 'kotlinx-serialization'
7 |
8 | }
9 |
10 | android {
11 | compileSdk 32
12 |
13 | defaultConfig {
14 | applicationId "com.mutualmobile.currencyconvertermm"
15 | minSdk 26
16 | targetSdk 32
17 | versionCode 1
18 | versionName "1.0"
19 |
20 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
21 | vectorDrawables {
22 | useSupportLibrary true
23 | }
24 | }
25 |
26 | buildTypes {
27 | release {
28 | minifyEnabled false
29 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
30 | }
31 | }
32 | compileOptions {
33 | sourceCompatibility JavaVersion.VERSION_1_8
34 | targetCompatibility JavaVersion.VERSION_1_8
35 | }
36 | kotlinOptions {
37 | jvmTarget = '1.8'
38 | }
39 | buildFeatures {
40 | compose true
41 | }
42 | composeOptions {
43 | kotlinCompilerExtensionVersion compose_version
44 | }
45 | packagingOptions {
46 | resources {
47 | excludes += '/META-INF/{AL2.0,LGPL2.1}'
48 | }
49 | }
50 | }
51 |
52 | dependencies {
53 | implementation project(":domain")
54 | implementation project(":data")
55 |
56 | implementation "com.google.dagger:hilt-android:2.40.5"
57 | implementation 'androidx.test:core-ktx:1.4.0'
58 | implementation 'androidx.test.ext:junit-ktx:1.1.3'
59 | kapt "com.google.dagger:hilt-compiler:2.40.5"
60 | def activity_version = "1.4.0"
61 |
62 | implementation "androidx.activity:activity-ktx:$activity_version"
63 |
64 | api 'io.ktor:ktor-client-android:2.0.1'
65 | api 'io.ktor:ktor-client-logging-jvm:2.0.1'
66 |
67 | api("androidx.room:room-runtime:2.4.2")
68 | kapt("androidx.room:room-compiler:2.4.2")
69 | api "androidx.room:room-ktx:2.4.2"
70 | api("androidx.room:room-paging:2.4.2")
71 | implementation("androidx.paging:paging-compose:1.0.0-alpha15")
72 |
73 | def work_version = "2.7.1"
74 | implementation "androidx.work:work-runtime-ktx:$work_version"
75 | implementation 'androidx.hilt:hilt-work:1.0.0'
76 | kapt 'androidx.hilt:hilt-compiler:1.0.0'
77 |
78 |
79 | implementation 'androidx.core:core-ktx:1.8.0'
80 | implementation "androidx.compose.ui:ui:$compose_version"
81 | implementation "androidx.compose.material:material:$compose_version"
82 | implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
83 | implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
84 | implementation 'androidx.activity:activity-compose:1.4.0'
85 |
86 | testImplementation "io.mockk:mockk:1.12.0"
87 | testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.1"
88 | testImplementation "app.cash.turbine:turbine:0.7.0"
89 |
90 | androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.1"
91 | androidTestImplementation "app.cash.turbine:turbine:0.7.0"
92 |
93 | testImplementation 'junit:junit:4.13.2'
94 | implementation "androidx.datastore:datastore-preferences:1.0.0"
95 |
96 | androidTestImplementation 'androidx.test.ext:junit:1.1.3'
97 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
98 | androidTestImplementation "androidx.test:runner:1.4.0"
99 | androidTestImplementation "androidx.test:rules:1.4.0"
100 | androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
101 | debugImplementation("androidx.compose.ui:ui-test-manifest:$compose_version")
102 |
103 | debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
104 | debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
105 | }
--------------------------------------------------------------------------------
/data/src/main/java/com/paypay/data/local/CurrenciesLocalSourceImpl.kt:
--------------------------------------------------------------------------------
1 | package com.mm.data.local
2 |
3 | import androidx.datastore.core.DataStore
4 | import androidx.datastore.preferences.core.Preferences
5 | import androidx.datastore.preferences.core.edit
6 | import androidx.datastore.preferences.core.intPreferencesKey
7 | import androidx.datastore.preferences.core.longPreferencesKey
8 | import androidx.paging.Pager
9 | import androidx.paging.PagingConfig
10 | import androidx.paging.PagingData
11 | import androidx.paging.map
12 | import com.currency.domain.CurrenciesLocalSource
13 | import com.currency.domain.CurrencyConverter
14 | import com.currency.domain.CurrencyConverter.CURRENCIES_KEY
15 | import com.currency.domain.models.DMCurrency
16 | import com.currency.domain.models.DMLatestRate
17 | import com.mm.data.local.entities.LocalCurrency
18 | import kotlinx.coroutines.flow.Flow
19 | import kotlinx.coroutines.flow.firstOrNull
20 | import kotlinx.coroutines.flow.map
21 | import kotlinx.coroutines.flow.mapLatest
22 | import kotlinx.coroutines.withContext
23 | import java.util.*
24 | import java.util.concurrent.TimeUnit
25 | import javax.inject.Inject
26 | import kotlin.coroutines.CoroutineContext
27 |
28 | class CurrenciesLocalSourceImpl @Inject constructor(
29 | private val ccDatabase: CCDatabase,
30 | private val coroutineContext: CoroutineContext,
31 | private val dataStore: DataStore
32 | ) : CurrenciesLocalSource {
33 | private val currenciesTime = longPreferencesKey(CURRENCIES_KEY)
34 | private val latestPricesKey = longPreferencesKey(CurrencyConverter.LATEST_PRICES_KEY)
35 |
36 | override suspend fun canFetchCurrencies(): Boolean {
37 | val time = dataStore.data.map { preferences ->
38 | preferences[currenciesTime]
39 | }.firstOrNull()
40 | return time?.let {
41 | val savedTime = TimeUnit.MILLISECONDS.toMinutes(it.times(1000))
42 | val nowTime = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis())
43 | nowTime.minus(savedTime) > 30
44 | } ?: kotlin.run {
45 | true
46 | }
47 | }
48 |
49 | override suspend fun canFetchLatestRates(): Boolean {
50 | val time = dataStore.data.map { preferences ->
51 | preferences[latestPricesKey]
52 | }.firstOrNull()
53 | return time?.let {
54 | val savedTime = TimeUnit.MILLISECONDS.toMinutes(it.times(1000))
55 | val nowTime = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis())
56 | nowTime.minus(savedTime) > 30
57 | } ?: kotlin.run {
58 | true
59 | }
60 | }
61 |
62 | override suspend fun latestRatesFetchLastTime(): Date? {
63 | val time = dataStore.data.map { preferences ->
64 | preferences[latestPricesKey]
65 | }.firstOrNull()
66 | return time?.let {
67 | Date(it.times(1000))
68 | } ?: kotlin.run {
69 | null
70 | }
71 | }
72 |
73 | override fun fetchLocalCurrencies(searchKey: String?): Flow> {
74 | val data = searchKey?.takeIf { it.isNotEmpty() }?.let {
75 | ccDatabase.currenciesDao().currenciesByKey("%${searchKey}%")
76 | } ?: run {
77 | ccDatabase.currenciesDao().currenciesPaginated()
78 | }
79 |
80 | return data.mapLatest {
81 | it.map { DMCurrency(it.currency, it.name) }
82 | }
83 | }
84 |
85 | override fun fetchLocalRates(searchKey: String?, input: Double): Flow> {
86 | val data = searchKey?.takeIf { it.isNotEmpty() }?.let {
87 | ccDatabase.currenciesDao().currenciesByKey("%${searchKey}%")
88 | } ?: run {
89 | ccDatabase.currenciesDao().currenciesPaginated()
90 | }
91 | return data.mapLatest {
92 | it.map {
93 | DMLatestRate(
94 | it.currency,
95 | it.rate ?: 0.0, name = it.name
96 | )
97 | }
98 | }
99 | }
100 |
101 | override suspend fun saveCurrenciesLocally(currencies: Map) {
102 | withContext(coroutineContext) {
103 | ccDatabase.currenciesDao()
104 | .insertAll(currencies.map { LocalCurrency(it.key, it.value) })
105 | dataStore.edit { settings ->
106 | settings[currenciesTime] = System.currentTimeMillis() / 1000
107 | }
108 | }
109 |
110 | }
111 |
112 | override suspend fun saveLatestRates(rates: Map?) {
113 | withContext(coroutineContext) {
114 | rates?.entries?.forEach { (key, rate) ->
115 | ccDatabase.currenciesDao().updateCurrencyRates(key, rate)
116 | }
117 | dataStore.edit { settings ->
118 | settings[latestPricesKey] = System.currentTimeMillis() / 1000
119 | }
120 | }
121 |
122 | }
123 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/currency/currencyconvertermm/CurrencyConversionComposeUITests.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import android.content.Context
4 | import androidx.activity.viewModels
5 | import androidx.compose.ui.test.*
6 | import androidx.compose.ui.test.junit4.createComposeRule
7 | import androidx.datastore.preferences.core.PreferenceDataStoreFactory
8 | import androidx.datastore.preferences.preferencesDataStoreFile
9 | import androidx.room.Room
10 | import androidx.test.core.app.ApplicationProvider
11 | import androidx.test.ext.junit.runners.AndroidJUnit4
12 | import androidx.test.platform.app.InstrumentationRegistry
13 | import com.currency.currencyconvertermm.features.currencyconverter.CurrencyConverterVM
14 | import com.currency.currencyconvertermm.features.currencyconverter.composables.UICurrencyConverter
15 | import com.currency.currencyconvertermm.ui.theme.CurrencyConvertermmTheme
16 | import com.currency.domain.usecase.UseCaseFetchCurrencies
17 | import com.currency.domain.usecase.UseCaseFetchLatestPrices
18 | import com.currency.domain.usecase.UseCaseLoadCurrenciesDataFromNetwork
19 | import com.currency.domain.usecase.UseCaseLoadLatestPricesFromNetwork
20 | import com.mm.data.local.CCDatabase
21 | import com.mm.data.local.CurrenciesLocalSourceImpl
22 | import com.mm.data.network.CurrencyAPI
23 | import com.mm.data.repo.CurrenciesRepositoryImpl
24 | import com.mm.data.repo.LatestPricesRepositoryImpl
25 | import kotlinx.coroutines.Dispatchers
26 | import kotlinx.coroutines.ExperimentalCoroutinesApi
27 | import kotlinx.coroutines.delay
28 | import kotlinx.coroutines.launch
29 | import kotlinx.coroutines.test.StandardTestDispatcher
30 | import kotlinx.coroutines.test.resetMain
31 | import kotlinx.coroutines.test.runTest
32 | import kotlinx.coroutines.test.setMain
33 | import org.junit.After
34 | import org.junit.Before
35 | import org.junit.Rule
36 | import org.junit.Test
37 | import org.junit.runner.RunWith
38 |
39 | @RunWith(AndroidJUnit4::class)
40 | class CurrencyConversionComposeUITests {
41 |
42 | private var currencyAPI: CurrencyAPI = FakeCurrencyAPI()
43 | private val context = ApplicationProvider.getApplicationContext()
44 |
45 | private var networkInfoProvider = FakeNetworkInfoProvider()
46 | private val database = Room.inMemoryDatabaseBuilder(context, CCDatabase::class.java).build()
47 |
48 | val ds = PreferenceDataStoreFactory.create() {
49 | InstrumentationRegistry.getInstrumentation().targetContext.preferencesDataStoreFile(
50 | "test-preferences-file"
51 | )
52 | }
53 |
54 | private val currenciesLocalSource = CurrenciesLocalSourceImpl(
55 | database,Dispatchers.IO,ds
56 | )
57 |
58 | private val latestPricesRepository by lazy {
59 | LatestPricesRepositoryImpl(
60 | Dispatchers.Main,
61 | currencyAPI, currenciesLocalSource
62 | )
63 | }
64 | private val currenciesRepository by lazy {
65 | CurrenciesRepositoryImpl(
66 | Dispatchers.Main,
67 | currencyAPI, currenciesLocalSource
68 | )
69 | }
70 |
71 | private val useCaseFetchLatestPrices by lazy { UseCaseFetchLatestPrices(latestPricesRepository) }
72 | private val useCaseFetchCurrencies by lazy {
73 | UseCaseFetchCurrencies(currenciesRepository)
74 | }
75 |
76 |
77 | private val useCaseLoadCurrenciesDataFromNetwork by lazy {
78 | UseCaseLoadCurrenciesDataFromNetwork(
79 | currenciesRepository
80 | )
81 | }
82 |
83 | private val useCaseLoadLatestPricesFromNetwork by lazy {
84 | UseCaseLoadLatestPricesFromNetwork(latestPricesRepository)
85 | }
86 |
87 | private lateinit var currencyConverterVM: CurrencyConverterVM
88 |
89 | @get:Rule
90 | val composeTestRule = createComposeRule()
91 |
92 | @Test
93 | fun testConversions() {
94 | // Start the app
95 | networkInfoProvider.networkSwitch(true)
96 |
97 | currencyConverterVM = CurrencyConverterVM(
98 | useCaseLoadCurrenciesDataFromNetwork,
99 | useCaseLoadLatestPricesFromNetwork,
100 | useCaseFetchLatestPrices,
101 | useCaseFetchCurrencies,
102 | networkInfoProvider
103 | )
104 |
105 | composeTestRule.setContent {
106 | CurrencyConvertermmTheme {
107 | UICurrencyConverter(currencyConverterVM)
108 | }
109 | }
110 |
111 | composeTestRule.onNodeWithText(context.getString(R.string.converter_select_currency))
112 | .performTextInput("INR")
113 |
114 | composeTestRule.onNodeWithText("Indian Rupee").performClick()
115 |
116 | composeTestRule.onNodeWithText("Rate: 75.0").assertIsDisplayed()
117 |
118 | composeTestRule.onNodeWithText(context.getString(R.string.enter_amount))
119 | .performTextInput("50.0")
120 |
121 | composeTestRule.onNodeWithText("Converted: Indian Rupee to 3750.0")
122 | .assertIsDisplayed()
123 |
124 |
125 | }
126 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/CurrencyConverterVM.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import com.currency.currencyconvertermm.features.currencyconverter.exceptions.NetworkNotAvailableException
6 | import com.currency.domain.NetworkInfoProvider
7 | import com.currency.domain.models.DMCurrency
8 | import com.currency.domain.models.DMLatestRate
9 | import com.currency.domain.usecase.UseCaseFetchCurrencies
10 | import com.currency.domain.usecase.UseCaseFetchLatestPrices
11 | import com.currency.domain.usecase.UseCaseLoadCurrenciesDataFromNetwork
12 | import com.currency.domain.usecase.UseCaseLoadLatestPricesFromNetwork
13 | import dagger.hilt.android.lifecycle.HiltViewModel
14 | import kotlinx.coroutines.CoroutineExceptionHandler
15 | import kotlinx.coroutines.flow.*
16 | import kotlinx.coroutines.launch
17 | import java.util.*
18 | import javax.inject.Inject
19 |
20 | @HiltViewModel
21 | class CurrencyConverterVM @Inject constructor(
22 | private val useCaseLoadCurrenciesDataFromNetwork: UseCaseLoadCurrenciesDataFromNetwork,
23 | private val useCaseLoadLatestPricesFromNetwork: UseCaseLoadLatestPricesFromNetwork,
24 | private val useCaseFetchLatestPrices: UseCaseFetchLatestPrices,
25 | private val useCaseFetchCurrencies: UseCaseFetchCurrencies,
26 | private val networkInfoProvider: NetworkInfoProvider
27 | ) :
28 | ViewModel() {
29 |
30 | var viewState = MutableStateFlow(ViewState.Empty)
31 | private set
32 |
33 | var selectedCurrency = MutableStateFlow?>(null)
34 | var searchCurrency = MutableStateFlow("")
35 | var amountForConversion = MutableStateFlow("")
36 |
37 | private val _currenciesState = MutableStateFlow>>(emptyFlow())
38 | val currenciesState = _currenciesState.asStateFlow()
39 |
40 | private var _latestRatesState = MutableStateFlow>>(emptyFlow())
41 | val latestRatesState = _latestRatesState.asStateFlow()
42 |
43 | private val currenciesException = CoroutineExceptionHandler { _, throwable ->
44 | viewState.value = ViewState.Exception(throwable)
45 | }
46 |
47 | init {
48 | registerNetwork()
49 | forceFetchCurrenciesOnLaunch()
50 | registerOnSearchChangeFlow()
51 | registerOnAmountChangeFlow()
52 | }
53 |
54 | private fun registerNetwork() {
55 | networkInfoProvider.listenToChanges().onEach {
56 | onNetworkAvailable(it)
57 | }.launchIn(viewModelScope)
58 | }
59 |
60 | private fun onNetworkAvailable(available: Boolean?) {
61 | if (available == true) {
62 | // network is available now! Let's refresh the UI
63 | // with latest data if DataState.LoadComplete never encountered ?
64 | if (viewState.value !is ViewState.LoadComplete && viewState.value !is ViewState.Loading) {
65 | forceFetchCurrenciesOnLaunch()
66 | }
67 | }
68 | }
69 |
70 | private fun registerOnSearchChangeFlow() {
71 | searchCurrency.onEach { // on every search keystroke we update the flow
72 | _currenciesState.value = flowFetchCurrencies()
73 | }.launchIn(viewModelScope)
74 | }
75 |
76 | private fun registerOnAmountChangeFlow() {
77 | amountForConversion.onEach {
78 | _latestRatesState.value = flowFetchRates()
79 | }.launchIn(viewModelScope)
80 | }
81 |
82 |
83 | private fun forceFetchCurrenciesOnLaunch() {
84 | if (networkInfoProvider.hasNetwork()) {
85 | viewModelScope.launch(currenciesException) {
86 | // do this in launch
87 | viewState.value = ViewState.Loading
88 | useCaseLoadCurrenciesDataFromNetwork.perform()
89 | val completeDate = useCaseLoadLatestPricesFromNetwork.perform()
90 | viewState.value = ViewState.LoadComplete(completeDate)
91 | }
92 | } else {
93 | viewState.value =
94 | ViewState.Exception(NetworkNotAvailableException("No Network Available!"))
95 | }
96 | }
97 |
98 | private fun flowFetchCurrencies(): Flow> {
99 | return useCaseFetchCurrencies.perform(searchCurrency.value)
100 | }
101 |
102 | private fun flowFetchRates(): Flow> {
103 | return useCaseFetchLatestPrices.perform(amountForConversion.value)
104 |
105 | }
106 |
107 | fun updateCurrency(key: Pair) {
108 | amountForConversion.value = ""
109 | selectedCurrency.value = key
110 | searchCurrency.value = key.second
111 | }
112 |
113 | fun clearCurrency() {
114 | amountForConversion.value = ""
115 | selectedCurrency.value = null
116 | searchCurrency.value = ""
117 | }
118 |
119 | sealed class ViewState {
120 | object Empty : ViewState()
121 | object Loading : ViewState()
122 | data class LoadComplete(val date: Date) : ViewState()
123 | data class Exception(val throwable: Throwable) : ViewState()
124 | }
125 |
126 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/currency/currencyconvertermm/features/currencyconverter/composables/CurrencyConverterForm.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm.features.currencyconverter.composables
2 |
3 | import androidx.compose.animation.AnimatedVisibility
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.*
6 | import androidx.compose.material.*
7 | import androidx.compose.runtime.*
8 | import androidx.compose.ui.Alignment
9 | import androidx.compose.ui.ExperimentalComposeUiApi
10 | import androidx.compose.ui.Modifier
11 | import androidx.compose.ui.platform.LocalSoftwareKeyboardController
12 | import androidx.compose.ui.res.stringResource
13 | import androidx.compose.ui.text.font.FontWeight
14 | import androidx.compose.ui.unit.dp
15 | import com.currency.currencyconvertermm.features.currencyconverter.CurrencyConverterVM
16 | import com.currency.currencyconvertermm.R
17 | import com.currency.currencyconvertermm.features.currencyconverter.composables.common.CurrencyAutoComplete
18 | import com.currency.currencyconvertermm.features.currencyconverter.composables.common.CurrencyTextField
19 | import com.currency.currencyconvertermm.ui.theme.Typography
20 |
21 | @ExperimentalMaterialApi
22 | @Composable
23 | fun CurrencyConverterForm(modifier: Modifier = Modifier, viewModel: CurrencyConverterVM) {
24 | val amount by viewModel.amountForConversion.collectAsState()
25 | val selectedCurrency by viewModel.selectedCurrency.collectAsState()
26 | val dataState by viewModel.viewState.collectAsState()
27 | Box(modifier) {
28 | Column(horizontalAlignment = Alignment.CenterHorizontally) {
29 | when (dataState) {
30 | is CurrencyConverterVM.ViewState.Loading -> {
31 | Text(
32 | style = Typography.subtitle1.copy(
33 | fontWeight = FontWeight.Bold
34 | ),
35 | text = "Refreshing Rates...", modifier = Modifier
36 | .padding(12.dp)
37 | )
38 | }
39 | is CurrencyConverterVM.ViewState.Exception -> {
40 | Text(
41 | style = Typography.subtitle1.copy(
42 | fontWeight = FontWeight.Bold
43 | ),
44 | text = "Failed: ${(dataState as CurrencyConverterVM.ViewState.Exception).throwable.localizedMessage}",
45 | modifier = Modifier
46 | .padding(12.dp)
47 | )
48 | }
49 | CurrencyConverterVM.ViewState.Empty -> {
50 | Text(
51 | style = Typography.subtitle1.copy(
52 | fontWeight = FontWeight.Bold
53 | ),
54 | text = "Nothing to Show Here!", modifier = Modifier
55 | .padding(12.dp)
56 | )
57 | }
58 | is CurrencyConverterVM.ViewState.LoadComplete -> {
59 | Text(
60 | style = Typography.subtitle1.copy(
61 | fontWeight = FontWeight.Bold
62 | ), modifier = Modifier
63 | .padding(12.dp),
64 | text = "Rates Updated on, ${(dataState as CurrencyConverterVM.ViewState.LoadComplete).date}"
65 | )
66 | }
67 | }
68 | CurrenciesSelection(
69 | viewModel,
70 | Modifier
71 | .fillMaxWidth()
72 | .padding(8.dp)
73 | )
74 | AnimatedVisibility(visible = selectedCurrency != null) {
75 | CurrencyTextField(
76 | fieldValue = amount, onChange = { newAmount ->
77 | viewModel.amountForConversion.value = newAmount
78 | }, modifier = Modifier
79 | .fillMaxWidth()
80 | .padding(8.dp)
81 | )
82 | }
83 | RatesView(viewModel)
84 |
85 | }
86 | }
87 | }
88 |
89 | @OptIn(ExperimentalComposeUiApi::class)
90 | @ExperimentalMaterialApi
91 | @Composable
92 | fun CurrenciesSelection(viewModel: CurrencyConverterVM, modifier: Modifier = Modifier) {
93 | val controller = LocalSoftwareKeyboardController.current
94 |
95 | val currenciesStateFlow by viewModel.currenciesState.collectAsState()
96 | val currenciesState by currenciesStateFlow.collectAsState(initial = emptyList())
97 |
98 | val selectedCurrency by viewModel.selectedCurrency.collectAsState()
99 | val searchCurrency by viewModel.searchCurrency.collectAsState()
100 |
101 | Column(
102 | modifier = modifier
103 | .wrapContentSize(Alignment.TopStart)
104 | ) {
105 | selectedCurrency?.let { (key, value) ->
106 | SelectedCurrencyListItem(selectedCurrency, key, value, Modifier.clickable {
107 | viewModel.updateCurrency(Pair(key, value))
108 | }, onClearCurrency = {
109 | viewModel.clearCurrency()
110 | })
111 | } ?: run {
112 | CurrencyAutoComplete(
113 | query = searchCurrency,
114 | label = stringResource(R.string.converter_select_currency),
115 | isReadOnly = selectedCurrency != null,
116 | onQueryChanged = {
117 | viewModel.searchCurrency.value = it
118 | }, onDoneActionClick = {
119 | controller?.hide()
120 | }, onClearClick = {
121 | controller?.hide()
122 | })
123 | CurrencyList(
124 | currenciesState,
125 | ) { pair ->
126 | viewModel.updateCurrency(pair)
127 |
128 | }
129 | }
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/currency/currencyconvertermm/CurrencyVMTest.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import android.content.Context
4 | import androidx.datastore.preferences.core.PreferenceDataStoreFactory
5 | import androidx.datastore.preferences.preferencesDataStoreFile
6 | import androidx.room.Room
7 | import androidx.test.core.app.ApplicationProvider
8 | import androidx.test.ext.junit.runners.AndroidJUnit4
9 | import androidx.test.platform.app.InstrumentationRegistry
10 | import app.cash.turbine.test
11 | import com.currency.currencyconvertermm.features.currencyconverter.CurrencyConverterVM
12 | import com.currency.currencyconvertermm.features.currencyconverter.exceptions.NetworkNotAvailableException
13 | import com.currency.domain.usecase.UseCaseFetchCurrencies
14 | import com.currency.domain.usecase.UseCaseFetchLatestPrices
15 | import com.currency.domain.usecase.UseCaseLoadCurrenciesDataFromNetwork
16 | import com.currency.domain.usecase.UseCaseLoadLatestPricesFromNetwork
17 | import com.mm.data.local.CCDatabase
18 | import com.mm.data.local.CurrenciesLocalSourceImpl
19 | import com.mm.data.network.CurrencyAPI
20 | import com.mm.data.repo.CurrenciesRepositoryImpl
21 | import com.mm.data.repo.LatestPricesRepositoryImpl
22 | import kotlinx.coroutines.*
23 | import kotlinx.coroutines.test.StandardTestDispatcher
24 | import kotlinx.coroutines.test.resetMain
25 | import kotlinx.coroutines.test.runTest
26 | import kotlinx.coroutines.test.setMain
27 | import org.junit.After
28 | import org.junit.Before
29 | import org.junit.Test
30 | import org.junit.runner.RunWith
31 |
32 | @RunWith(AndroidJUnit4::class)
33 | class CurrencyConverterVMShould {
34 |
35 | private var currencyAPI: CurrencyAPI = FakeCurrencyAPI()
36 | private val context = ApplicationProvider.getApplicationContext()
37 |
38 | private var networkInfoProvider = FakeNetworkInfoProvider()
39 | private val database = Room.inMemoryDatabaseBuilder(context, CCDatabase::class.java).build()
40 |
41 | val ds = PreferenceDataStoreFactory.create() {
42 | InstrumentationRegistry.getInstrumentation().targetContext.preferencesDataStoreFile(
43 | "test-preferences-file"
44 | )
45 | }
46 |
47 | private val currenciesLocalSource = CurrenciesLocalSourceImpl(
48 | database,Dispatchers.IO,ds
49 | )
50 |
51 | private val latestPricesRepository by lazy {
52 | LatestPricesRepositoryImpl(
53 | Dispatchers.Main,
54 | currencyAPI, currenciesLocalSource
55 | )
56 | }
57 | private val currenciesRepository by lazy {
58 | CurrenciesRepositoryImpl(
59 | Dispatchers.Main,
60 | currencyAPI, currenciesLocalSource
61 | )
62 | }
63 |
64 | private val useCaseFetchLatestPrices by lazy { UseCaseFetchLatestPrices(latestPricesRepository) }
65 | private val useCaseFetchCurrencies by lazy {
66 | UseCaseFetchCurrencies(currenciesRepository)
67 | }
68 |
69 |
70 | private val useCaseLoadCurrenciesDataFromNetwork by lazy {
71 | UseCaseLoadCurrenciesDataFromNetwork(
72 | currenciesRepository
73 | )
74 | }
75 |
76 | private val useCaseLoadLatestPricesFromNetwork by lazy {
77 | UseCaseLoadLatestPricesFromNetwork(latestPricesRepository)
78 | }
79 |
80 | private lateinit var currencyConverterVM: CurrencyConverterVM
81 |
82 |
83 | @OptIn(ExperimentalCoroutinesApi::class)
84 | @Before
85 | fun setUp() {
86 | Dispatchers.setMain(StandardTestDispatcher())
87 | }
88 |
89 |
90 | @OptIn(ExperimentalCoroutinesApi::class)
91 | @After
92 | fun tearDown() {
93 | Dispatchers.resetMain()
94 | }
95 |
96 | @Test
97 | fun throwNetworkExceptionWhenNetworkNotAvailale() {
98 | runTest {
99 | launch {
100 | networkInfoProvider.networkSwitch(false)
101 |
102 | currencyConverterVM = CurrencyConverterVM(
103 | useCaseLoadCurrenciesDataFromNetwork,
104 | useCaseLoadLatestPricesFromNetwork,
105 | useCaseFetchLatestPrices,
106 | useCaseFetchCurrencies,
107 | networkInfoProvider
108 | )
109 |
110 | currencyConverterVM.viewState.test {
111 | val firstItem = awaitItem()
112 | assert(firstItem is CurrencyConverterVM.ViewState.Exception && firstItem.throwable is NetworkNotAvailableException)
113 | awaitComplete()
114 | }
115 | }
116 | }
117 | }
118 |
119 |
120 | @OptIn(ExperimentalCoroutinesApi::class)
121 | @Test
122 | fun returnCurrenciesWhenReceivedFromNetworkAndSavedIntoDatabase() {
123 | runTest {
124 | launch {
125 | networkInfoProvider.networkSwitch(true)
126 |
127 | currencyConverterVM = CurrencyConverterVM(
128 | useCaseLoadCurrenciesDataFromNetwork,
129 | useCaseLoadLatestPricesFromNetwork,
130 | useCaseFetchLatestPrices,
131 | useCaseFetchCurrencies,
132 | networkInfoProvider
133 | )
134 |
135 | currencyConverterVM.viewState.test {
136 | assert(awaitItem() is CurrencyConverterVM.ViewState.Empty)
137 | assert(awaitItem() is CurrencyConverterVM.ViewState.Loading)
138 | val lastComplete = awaitItem()
139 | assert(lastComplete is CurrencyConverterVM.ViewState.LoadComplete)
140 | val dataSet = database.currenciesDao().getAll()
141 | assert(dataSet.isNotEmpty() && dataSet.size == 2)
142 | awaitComplete()
143 | }
144 | }
145 | }
146 | }
147 |
148 | @OptIn(ExperimentalCoroutinesApi::class)
149 | @Test
150 | fun testThatThenUserInputsTheCurrencyWeGeTheCalculatedAmount() {
151 | runTest {
152 | launch {
153 | val amountToConvert = 45.0
154 |
155 | networkInfoProvider.networkSwitch(true)
156 |
157 | currencyConverterVM = CurrencyConverterVM(
158 | useCaseLoadCurrenciesDataFromNetwork,
159 | useCaseLoadLatestPricesFromNetwork,
160 | useCaseFetchLatestPrices,
161 | useCaseFetchCurrencies,
162 | networkInfoProvider
163 | )
164 | currencyConverterVM.amountForConversion.value = amountToConvert.toString()
165 | delay(10)
166 | currencyConverterVM.latestRatesState.value.test {
167 | val pagingData = awaitItem()
168 | assert(pagingData.size == 2)
169 | assert(pagingData.first().calculatedRate(amountToConvert) == pagingData.first().rate.times(amountToConvert))
170 | awaitComplete()
171 | }
172 |
173 | }
174 | }
175 | }
176 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/currency/currencyconvertermm/CurrencyVMTest.kt:
--------------------------------------------------------------------------------
1 | package com.currency.currencyconvertermm
2 |
3 | import app.cash.turbine.test
4 | import com.currency.currencyconvertermm.features.currencyconverter.CurrencyConverterVM
5 | import com.currency.currencyconvertermm.features.currencyconverter.exceptions.NetworkNotAvailableException
6 | import com.currency.domain.NetworkInfoProvider
7 | import com.currency.domain.usecase.UseCaseFetchCurrencies
8 | import com.currency.domain.usecase.UseCaseFetchLatestPrices
9 | import com.currency.domain.usecase.UseCaseLoadCurrenciesDataFromNetwork
10 | import com.currency.domain.usecase.UseCaseLoadLatestPricesFromNetwork
11 | import com.mm.data.network.CurrencyAPI
12 | import com.mm.data.network.NetLatestRates
13 | import com.mm.data.repo.CurrenciesRepositoryImpl
14 | import com.mm.data.repo.LatestPricesRepositoryImpl
15 | import io.mockk.MockKAnnotations
16 | import io.mockk.coEvery
17 | import io.mockk.every
18 | import io.mockk.impl.annotations.MockK
19 | import kotlinx.coroutines.Dispatchers
20 | import kotlinx.coroutines.ExperimentalCoroutinesApi
21 | import kotlinx.coroutines.delay
22 | import kotlinx.coroutines.flow.emptyFlow
23 | import kotlinx.coroutines.launch
24 | import kotlinx.coroutines.test.StandardTestDispatcher
25 | import kotlinx.coroutines.test.resetMain
26 | import kotlinx.coroutines.test.runTest
27 | import kotlinx.coroutines.test.setMain
28 | import org.junit.After
29 | import org.junit.Before
30 | import org.junit.Test
31 |
32 | class CurrencyConverterVMShould {
33 |
34 | @MockK
35 | lateinit var currencyAPI: CurrencyAPI
36 |
37 | var currenciesLocalSource = FakeCurrenciesLocalSource()
38 |
39 | @MockK
40 | private lateinit var networkInfoProvider: NetworkInfoProvider
41 |
42 | private val latestPricesRepository by lazy {
43 | LatestPricesRepositoryImpl(
44 | Dispatchers.Main,
45 | currencyAPI, currenciesLocalSource
46 | )
47 | }
48 | private val currenciesRepository by lazy {
49 | CurrenciesRepositoryImpl(
50 | Dispatchers.Main,
51 | currencyAPI, currenciesLocalSource
52 | )
53 | }
54 |
55 | private val useCaseFetchLatestPrices by lazy { UseCaseFetchLatestPrices(latestPricesRepository) }
56 | private val useCaseFetchCurrencies by lazy {
57 | UseCaseFetchCurrencies(currenciesRepository)
58 | }
59 |
60 | private val useCaseLoadCurrenciesDataFromNetwork by lazy {
61 | UseCaseLoadCurrenciesDataFromNetwork(
62 | currenciesRepository
63 | )
64 | }
65 |
66 | private val useCaseLoadLatestPricesFromNetwork by lazy {
67 | UseCaseLoadLatestPricesFromNetwork(latestPricesRepository)
68 | }
69 |
70 | private lateinit var currencyConverterVM: CurrencyConverterVM
71 |
72 |
73 | @OptIn(ExperimentalCoroutinesApi::class)
74 | @Before
75 | fun setUp() {
76 | MockKAnnotations.init(this, true)
77 | Dispatchers.setMain(StandardTestDispatcher())
78 | }
79 |
80 |
81 | @OptIn(ExperimentalCoroutinesApi::class)
82 | @After
83 | fun tearDown() {
84 | Dispatchers.resetMain()
85 | }
86 |
87 | @OptIn(ExperimentalCoroutinesApi::class)
88 | @Test
89 | fun testthatwhennetworkisnotavailableitthrowsnetworkexception() {
90 | runTest {
91 |
92 | launch {
93 | coEvery { currencyAPI.networkFetchCurrencies() } returns hashMapOf().apply {
94 | put("INR", "Indian Rupee")
95 | put("XYZ", "XYZ currency")
96 | }
97 |
98 | coEvery { currencyAPI.networkFetchLatestRates() } returns NetLatestRates(rates = hashMapOf().apply {
99 | put("INR", 75.0)
100 | put("XYZ", 100.0)
101 | })
102 |
103 | every {
104 | networkInfoProvider.listenToChanges()
105 | } returns emptyFlow()
106 |
107 | every {
108 | networkInfoProvider.hasNetwork()
109 | } returns false
110 |
111 |
112 |
113 | currencyConverterVM = CurrencyConverterVM(
114 | useCaseLoadCurrenciesDataFromNetwork,
115 | useCaseLoadLatestPricesFromNetwork,
116 | useCaseFetchLatestPrices,
117 | useCaseFetchCurrencies,
118 | networkInfoProvider
119 | )
120 |
121 | currencyConverterVM.viewState.test {
122 | val firstItem = awaitItem()
123 | assert(firstItem is CurrencyConverterVM.ViewState.Exception && firstItem.throwable is NetworkNotAvailableException)
124 | awaitComplete()
125 | }
126 | }
127 | }
128 | }
129 |
130 |
131 | @OptIn(ExperimentalCoroutinesApi::class)
132 | @Test
133 | fun testthatwhennetworkisavailableitreturnscurrenciesintheflow() {
134 | runTest {
135 | launch {
136 | coEvery { currencyAPI.networkFetchCurrencies() } returns hashMapOf().apply {
137 | put("INR", "Indian Rupee")
138 | put("XYZ", "XYZ currency")
139 | }
140 |
141 | coEvery { currencyAPI.networkFetchLatestRates() } returns NetLatestRates(rates = hashMapOf().apply {
142 | put("INR", 75.0)
143 | put("XYZ", 100.0)
144 | })
145 |
146 | every {
147 | networkInfoProvider.listenToChanges()
148 | } returns emptyFlow()
149 |
150 | every {
151 | networkInfoProvider.hasNetwork()
152 | } returns true
153 |
154 |
155 |
156 | currencyConverterVM = CurrencyConverterVM(
157 | useCaseLoadCurrenciesDataFromNetwork,
158 | useCaseLoadLatestPricesFromNetwork,
159 | useCaseFetchLatestPrices,
160 | useCaseFetchCurrencies,
161 | networkInfoProvider
162 | )
163 |
164 | currencyConverterVM.viewState.test {
165 | assert(awaitItem() is CurrencyConverterVM.ViewState.Empty)
166 | assert(awaitItem() is CurrencyConverterVM.ViewState.Loading)
167 | val lastComplete = awaitItem()
168 | assert(lastComplete is CurrencyConverterVM.ViewState.LoadComplete)
169 | awaitComplete()
170 | }
171 | }
172 | }
173 | }
174 |
175 | @OptIn(ExperimentalCoroutinesApi::class)
176 | @Test
177 | fun testThatThenUserInputsTheCurrencyWeGeTheCalculatedAmount() {
178 | runTest {
179 | launch {
180 | val amountToConvert = 45.0
181 |
182 | coEvery { currencyAPI.networkFetchCurrencies() } returns hashMapOf().apply {
183 | put("INR", "Indian Rupee")
184 | put("XYZ", "XYZ currency")
185 | }
186 |
187 | coEvery { currencyAPI.networkFetchLatestRates() } returns NetLatestRates(rates = hashMapOf().apply {
188 | put("INR", 75.0)
189 | put("XYZ", 100.0)
190 | })
191 |
192 | every {
193 | networkInfoProvider.listenToChanges()
194 | } returns emptyFlow()
195 |
196 | every {
197 | networkInfoProvider.hasNetwork()
198 | } returns true
199 |
200 | currencyConverterVM = CurrencyConverterVM(
201 | useCaseLoadCurrenciesDataFromNetwork,
202 | useCaseLoadLatestPricesFromNetwork,
203 | useCaseFetchLatestPrices,
204 | useCaseFetchCurrencies,
205 | networkInfoProvider
206 | )
207 | currencyConverterVM.amountForConversion.value = amountToConvert.toString()
208 | delay(10)
209 | currencyConverterVM.latestRatesState.value.test {
210 | val pagingData = awaitItem()
211 | assert(pagingData.size == 2)
212 | assert(
213 | pagingData.first()
214 | .calculatedRate(amountToConvert) == pagingData.first().rate.times(
215 | amountToConvert
216 | )
217 | )
218 | awaitComplete()
219 | }
220 |
221 | }
222 | }
223 | }
224 |
225 | }
--------------------------------------------------------------------------------