├── .idea
├── .name
├── .gitignore
├── vcs.xml
├── compiler.xml
├── kotlinc.xml
├── other.xml
├── migrations.xml
├── misc.xml
├── gradle.xml
├── deploymentTargetDropDown.xml
└── inspectionProfiles
│ └── Project_Default.xml
├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── themes.xml
│ │ │ │ └── colors.xml
│ │ │ ├── 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
│ │ │ ├── mipmap-anydpi
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ │ └── drawable
│ │ │ │ ├── ic_arrow_back.xml
│ │ │ │ ├── ic_launcher_foreground.xml
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── androidfactory
│ │ │ │ └── simplerick
│ │ │ │ ├── SimpleRickApplication.kt
│ │ │ │ ├── utils
│ │ │ │ └── CharacterStatusUtils.kt
│ │ │ │ ├── repositories
│ │ │ │ ├── EpisodesRepository.kt
│ │ │ │ └── CharacterRepository.kt
│ │ │ │ ├── di
│ │ │ │ └── NetworkModule.kt
│ │ │ │ ├── ui
│ │ │ │ └── theme
│ │ │ │ │ ├── Color.kt
│ │ │ │ │ ├── Type.kt
│ │ │ │ │ └── Theme.kt
│ │ │ │ ├── components
│ │ │ │ ├── common
│ │ │ │ │ ├── LoadingState.kt
│ │ │ │ │ ├── CharacterNameComponent.kt
│ │ │ │ │ ├── DataPointComponent.kt
│ │ │ │ │ ├── CharacterImage.kt
│ │ │ │ │ └── SimpleToolbar.kt
│ │ │ │ ├── character
│ │ │ │ │ ├── CharacterDetailsNamePlateComponent.kt
│ │ │ │ │ ├── CharacterStatusCircle.kt
│ │ │ │ │ ├── CharacterStatusComponent.kt
│ │ │ │ │ ├── CharacterGridItem.kt
│ │ │ │ │ └── CharacterListItem.kt
│ │ │ │ └── episode
│ │ │ │ │ └── EpisodeRowComponent.kt
│ │ │ │ ├── viewmodels
│ │ │ │ ├── AllEpisodesViewModel.kt
│ │ │ │ ├── HomeScreenViewModel.kt
│ │ │ │ ├── CharacterDetailsViewModel.kt
│ │ │ │ └── SearchViewModel.kt
│ │ │ │ ├── screens
│ │ │ │ ├── HomeScreen.kt
│ │ │ │ ├── AllEpisodesScreen.kt
│ │ │ │ ├── CharacterDetailsScreen.kt
│ │ │ │ ├── CharacterEpisodeScreen.kt
│ │ │ │ └── SearchScreen.kt
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── androidfactory
│ │ │ └── simplerick
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── androidfactory
│ │ └── simplerick
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── network
├── .gitignore
├── consumer-rules.pro
├── src
│ ├── main
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ │ └── com
│ │ │ └── androidfactory
│ │ │ └── network
│ │ │ ├── models
│ │ │ ├── domain
│ │ │ │ ├── CharacterStatus.kt
│ │ │ │ ├── Episode.kt
│ │ │ │ ├── EpisodePage.kt
│ │ │ │ ├── CharacterGender.kt
│ │ │ │ ├── CharacterPage.kt
│ │ │ │ └── Character.kt
│ │ │ └── remote
│ │ │ │ ├── RemoteEpisode.kt
│ │ │ │ ├── RemoteEpisodePage.kt
│ │ │ │ ├── RemoteCharacterPage.kt
│ │ │ │ └── RemoteCharacter.kt
│ │ │ └── KtorClient.kt
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── androidfactory
│ │ │ └── network
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── androidfactory
│ │ └── network
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── .gitignore
├── settings.gradle.kts
├── gradle.properties
├── gradlew.bat
└── gradlew
/.idea/.name:
--------------------------------------------------------------------------------
1 | Simple Rick
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/network/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/network/consumer-rules.pro:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Simple Rick
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/the-android-factory/SimpleRick/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/other.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/network/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/SimpleRickApplication.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick
2 |
3 | import android.app.Application
4 | import dagger.hilt.android.HiltAndroidApp
5 |
6 | @HiltAndroidApp
7 | class SimpleRickApplication: Application() {
8 | }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Nov 26 20:44:52 EST 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/.idea/migrations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/domain/CharacterStatus.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.domain
2 |
3 | sealed class CharacterStatus(val displayName: String) {
4 | object Alive: CharacterStatus("Alive")
5 | object Dead: CharacterStatus("Dead")
6 | object Unknown: CharacterStatus("Unknown")
7 | }
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/domain/Episode.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.domain
2 |
3 | data class Episode(
4 | val id: Int,
5 | val name: String,
6 | val seasonNumber: Int,
7 | val episodeNumber: Int,
8 | val airDate: String,
9 | val characterIdsInEpisode: List
10 | )
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/domain/EpisodePage.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.domain
2 |
3 | data class EpisodePage(
4 | val info: Info,
5 | val episodes: List
6 | ) {
7 | data class Info(
8 | val count: Int,
9 | val pages: Int,
10 | val next: String?,
11 | val prev: String?
12 | )
13 | }
14 |
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/domain/CharacterGender.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.domain
2 |
3 | sealed class CharacterGender(val displayName: String) {
4 | object Male: CharacterGender("Male")
5 | object Female: CharacterGender("Female")
6 | object Genderless: CharacterGender("No gender")
7 | object Unknown: CharacterGender("Not specified")
8 | }
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/domain/CharacterPage.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.domain
2 |
3 | data class CharacterPage(
4 | val info: Info,
5 | val characters: List
6 | ) {
7 | data class Info(
8 | val count: Int,
9 | val pages: Int,
10 | val next: String?,
11 | val prev: String?
12 | )
13 | }
14 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google()
4 | mavenCentral()
5 | gradlePluginPortal()
6 | }
7 | }
8 | dependencyResolutionManagement {
9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
10 | repositories {
11 | google()
12 | mavenCentral()
13 | }
14 | }
15 |
16 | rootProject.name = "Simple Rick"
17 | include(":app")
18 | include(":network")
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/utils/CharacterStatusUtils.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.utils
2 |
3 | import androidx.compose.ui.graphics.Color
4 | import com.androidfactory.network.models.domain.CharacterStatus
5 |
6 | fun CharacterStatus.asColor(): Color {
7 | return when (this) {
8 | CharacterStatus.Alive -> Color.Green
9 | CharacterStatus.Dead -> Color.Red
10 | CharacterStatus.Unknown -> Color.Yellow
11 | }
12 | }
--------------------------------------------------------------------------------
/network/src/test/java/com/androidfactory/network/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network
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 | }
--------------------------------------------------------------------------------
/app/src/test/java/com/androidfactory/simplerick/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick
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 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/repositories/EpisodesRepository.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.repositories
2 |
3 | import com.androidfactory.network.ApiOperation
4 | import com.androidfactory.network.KtorClient
5 | import com.androidfactory.network.models.domain.Episode
6 | import javax.inject.Inject
7 |
8 | class EpisodesRepository @Inject constructor(private val ktorClient: KtorClient) {
9 |
10 | suspend fun fetchAllEpisodes(): ApiOperation> = ktorClient.getAllEpisodes()
11 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/di/NetworkModule.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.di
2 |
3 | import com.androidfactory.network.KtorClient
4 | import dagger.Module
5 | import dagger.Provides
6 | import dagger.hilt.InstallIn
7 | import dagger.hilt.components.SingletonComponent
8 | import javax.inject.Singleton
9 |
10 | @Module
11 | @InstallIn(SingletonComponent::class)
12 | class NetworkModule {
13 |
14 | @Provides
15 | @Singleton
16 | fun providesKtorClient(): KtorClient {
17 | return KtorClient()
18 | }
19 | }
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_arrow_back.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.ui.theme
2 |
3 | import androidx.compose.ui.graphics.Color
4 |
5 | val Purple80 = Color(0xFFD0BCFF)
6 | val PurpleGrey80 = Color(0xFFCCC2DC)
7 | val Pink80 = Color(0xFFEFB8C8)
8 |
9 | val Purple40 = Color(0xFF6650a4)
10 | val PurpleGrey40 = Color(0xFF625b71)
11 | val Pink40 = Color(0xFF7D5260)
12 |
13 | val RickPrimary = Color(0xff262d3a)
14 | val RickAction = Color(0xffb5eefd)
15 | val RickSurface = Color(0xffead7ce)
16 | val RickTextPrimary = Color(0xffffffff)
17 | val RickTextSecondary = Color(0xffead7ce)
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/domain/Character.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.domain
2 |
3 | data class Character(
4 | val created: String,
5 | val episodeIds: List,
6 | val gender: CharacterGender,
7 | val id: Int,
8 | val imageUrl: String,
9 | val location: Location,
10 | val name: String,
11 | val origin: Origin,
12 | val species: String,
13 | val status: CharacterStatus,
14 | val type: String
15 | ) {
16 | data class Location(
17 | val name: String,
18 | val url: String
19 | )
20 |
21 | data class Origin(
22 | val name: String,
23 | val url: String
24 | )
25 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/common/LoadingState.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.common
2 |
3 | import androidx.compose.foundation.layout.fillMaxSize
4 | import androidx.compose.foundation.layout.padding
5 | import androidx.compose.material3.CircularProgressIndicator
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.ui.Modifier
8 | import androidx.compose.ui.unit.dp
9 | import com.androidfactory.simplerick.ui.theme.RickAction
10 |
11 | private val defaultModifier = Modifier
12 | .fillMaxSize()
13 | .padding(all = 128.dp)
14 |
15 | @Composable
16 | fun LoadingState(modifier: Modifier = defaultModifier) {
17 | CircularProgressIndicator(
18 | modifier = modifier,
19 | color = RickAction
20 | )
21 | }
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/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
--------------------------------------------------------------------------------
/.idea/deploymentTargetDropDown.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/common/CharacterNameComponent.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.common
2 |
3 | import androidx.compose.material3.Text
4 | import androidx.compose.runtime.Composable
5 | import androidx.compose.ui.text.font.FontWeight
6 | import androidx.compose.ui.tooling.preview.Preview
7 | import androidx.compose.ui.unit.sp
8 | import com.androidfactory.simplerick.ui.theme.RickAction
9 |
10 | @Composable
11 | fun CharacterNameComponent(name: String) {
12 | Text(
13 | text = name,
14 | fontSize = 42.sp,
15 | lineHeight = 42.sp,
16 | fontWeight = FontWeight.Bold,
17 | color = RickAction
18 | )
19 | }
20 |
21 | @Preview
22 | @Composable
23 | private fun CharacterNameComponentPreview() {
24 | CharacterNameComponent(name = "Rick Sanchez")
25 | }
--------------------------------------------------------------------------------
/network/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/androidfactory/simplerick/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick
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.androidfactory.simplerick", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/network/src/androidTest/java/com/androidfactory/network/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network
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.androidfactory.network.test", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/remote/RemoteEpisode.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.remote
2 |
3 | import com.androidfactory.network.models.domain.Episode
4 | import kotlinx.serialization.Serializable
5 |
6 | @Serializable
7 | data class RemoteEpisode(
8 | val id: Int,
9 | val name: String,
10 | val episode: String,
11 | val air_date: String,
12 | val characters: List
13 | )
14 |
15 | fun RemoteEpisode.toDomainEpisode(): Episode {
16 | return Episode(
17 | id = id,
18 | name = name,
19 | seasonNumber = episode.filter { it.isDigit() }.take(2).toInt(),
20 | episodeNumber = episode.filter { it.isDigit() }.takeLast(2).toInt(),
21 | airDate = air_date,
22 | characterIdsInEpisode = characters.map {
23 | it.substring(startIndex = it.lastIndexOf("/") + 1).toInt()
24 | }
25 | )
26 | }
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/remote/RemoteEpisodePage.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.remote
2 |
3 | import com.androidfactory.network.models.domain.EpisodePage
4 | import kotlinx.serialization.Serializable
5 |
6 | @Serializable
7 | data class RemoteEpisodePage(
8 | val info: Info,
9 | val results: List
10 | ) {
11 | @Serializable
12 | data class Info(
13 | val count: Int,
14 | val pages: Int,
15 | val next: String?,
16 | val prev: String?
17 | )
18 | }
19 |
20 | fun RemoteEpisodePage.toDomainEpisodePage(): EpisodePage {
21 | return EpisodePage(
22 | info = EpisodePage.Info(
23 | count = info.count,
24 | pages = info.pages,
25 | next = info.next,
26 | prev = info.prev
27 | ),
28 | episodes = results.map { it.toDomainEpisode() }
29 | )
30 | }
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/remote/RemoteCharacterPage.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.remote
2 |
3 | import com.androidfactory.network.models.domain.CharacterPage
4 | import kotlinx.serialization.Serializable
5 |
6 | @Serializable
7 | data class RemoteCharacterPage(
8 | val info: Info,
9 | val results: List
10 | ) {
11 | @Serializable
12 | data class Info(
13 | val count: Int,
14 | val pages: Int,
15 | val next: String?,
16 | val prev: String?
17 | )
18 | }
19 |
20 | fun RemoteCharacterPage.toDomainCharacterPage(): CharacterPage {
21 | return CharacterPage(
22 | info = CharacterPage.Info(
23 | count = info.count,
24 | pages = info.pages,
25 | next = info.next,
26 | prev = info.next
27 | ),
28 | characters = results.map { it.toDomainCharacter() }
29 | )
30 | }
31 |
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/repositories/CharacterRepository.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.repositories
2 |
3 | import com.androidfactory.network.ApiOperation
4 | import com.androidfactory.network.KtorClient
5 | import com.androidfactory.network.models.domain.Character
6 | import com.androidfactory.network.models.domain.CharacterPage
7 | import javax.inject.Inject
8 |
9 | class CharacterRepository @Inject constructor(private val ktorClient: KtorClient) {
10 | suspend fun fetchCharacterPage(
11 | page: Int,
12 | params: Map = emptyMap()
13 | ): ApiOperation {
14 | return ktorClient.getCharacterByPage(pageNumber = page, queryParams = params)
15 | }
16 |
17 | suspend fun fetchCharacter(characterId: Int): ApiOperation {
18 | return ktorClient.getCharacter(characterId)
19 | }
20 |
21 | suspend fun fetchAllCharactersByName(searchQuery: String): ApiOperation> {
22 | return ktorClient.searchAllCharactersByName(searchQuery)
23 | }
24 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp
17 | )
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
16 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/network/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.library)
3 | alias(libs.plugins.kotlin.android)
4 | alias(libs.plugins.kotlin.serialization)
5 | }
6 |
7 | android {
8 | namespace = "com.androidfactory.network"
9 | compileSdk = libs.versions.compileSdk.get().toInt()
10 |
11 | defaultConfig {
12 | minSdk = libs.versions.minSdk.get().toInt()
13 |
14 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
15 | consumerProguardFiles("consumer-rules.pro")
16 | }
17 |
18 | buildTypes {
19 | release {
20 | isMinifyEnabled = false
21 | proguardFiles(
22 | getDefaultProguardFile("proguard-android-optimize.txt"),
23 | "proguard-rules.pro"
24 | )
25 | }
26 | }
27 | compileOptions {
28 | sourceCompatibility = JavaVersion.VERSION_11
29 | targetCompatibility = JavaVersion.VERSION_11
30 | }
31 | kotlinOptions {
32 | jvmTarget = JavaVersion.VERSION_11.toString()
33 | }
34 | }
35 |
36 | dependencies {
37 |
38 | implementation(libs.bundles.ktor)
39 |
40 | testImplementation(libs.junit)
41 | androidTestImplementation(libs.ext.junit)
42 | androidTestImplementation(libs.espresso.core)
43 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/common/DataPointComponent.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.common
2 |
3 | import androidx.compose.foundation.layout.Column
4 | import androidx.compose.material3.Text
5 | import androidx.compose.runtime.Composable
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.tooling.preview.Preview
8 | import androidx.compose.ui.unit.sp
9 | import com.androidfactory.simplerick.ui.theme.RickAction
10 | import com.androidfactory.simplerick.ui.theme.RickTextPrimary
11 |
12 | data class DataPoint(
13 | val title: String,
14 | val description: String
15 | )
16 |
17 | @Composable
18 | fun DataPointComponent(dataPoint: DataPoint) {
19 | Column {
20 | Text(
21 | text = dataPoint.title,
22 | fontSize = 12.sp,
23 | fontWeight = FontWeight.Bold,
24 | color = RickAction
25 | )
26 | Text(
27 | text = dataPoint.description,
28 | fontSize = 18.sp,
29 | color = RickTextPrimary
30 | )
31 | }
32 | }
33 |
34 | @Preview
35 | @Composable
36 | fun DataPointComponentPreview() {
37 | val data = DataPoint(title = "Last known location", description = "Citadel of Ricks")
38 | DataPointComponent(dataPoint = data)
39 | }
--------------------------------------------------------------------------------
/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/androidfactory/simplerick/components/common/CharacterImage.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.common
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.layout.aspectRatio
5 | import androidx.compose.foundation.layout.fillMaxWidth
6 | import androidx.compose.foundation.shape.RoundedCornerShape
7 | import androidx.compose.runtime.Composable
8 | import androidx.compose.ui.Modifier
9 | import androidx.compose.ui.draw.clip
10 | import androidx.compose.ui.graphics.Brush
11 | import androidx.compose.ui.graphics.Color
12 | import androidx.compose.ui.tooling.preview.Preview
13 | import androidx.compose.ui.unit.dp
14 | import coil.compose.SubcomposeAsyncImage
15 |
16 | private val defaultModifier = Modifier
17 | .fillMaxWidth()
18 | .aspectRatio(1f)
19 | .clip(RoundedCornerShape(12.dp))
20 |
21 | @Composable
22 | fun CharacterImage(imageUrl: String, modifier: Modifier = defaultModifier) {
23 | SubcomposeAsyncImage(
24 | model = imageUrl,
25 | contentDescription = "Character image",
26 | modifier = modifier,
27 | loading = { LoadingState() }
28 | )
29 | }
30 |
31 | @Preview
32 | @Composable
33 | private fun CharacterImagePreview() {
34 | CharacterImage(
35 | imageUrl = "image url",
36 | modifier = defaultModifier.then(
37 | Modifier.background(
38 | brush = Brush.verticalGradient(listOf(Color.White, Color.Black))
39 | )
40 | )
41 | )
42 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/character/CharacterDetailsNamePlateComponent.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.character
2 |
3 | import androidx.compose.foundation.layout.Column
4 | import androidx.compose.foundation.layout.fillMaxWidth
5 | import androidx.compose.material3.Text
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.ui.Modifier
8 | import androidx.compose.ui.text.font.FontWeight
9 | import androidx.compose.ui.tooling.preview.Preview
10 | import androidx.compose.ui.unit.sp
11 | import com.androidfactory.network.models.domain.CharacterStatus
12 | import com.androidfactory.simplerick.components.common.CharacterNameComponent
13 | import com.androidfactory.simplerick.ui.theme.RickAction
14 |
15 | @Composable
16 | fun CharacterDetailsNamePlateComponent(name: String, status: CharacterStatus) {
17 | Column(modifier = Modifier.fillMaxWidth()) {
18 | CharacterStatusComponent(characterStatus = status)
19 | CharacterNameComponent(name = name)
20 | }
21 | }
22 |
23 | @Preview
24 | @Composable
25 | fun NamePlatePreviewAlive() {
26 | CharacterDetailsNamePlateComponent(name = "Rick Sanchez", status = CharacterStatus.Alive)
27 | }
28 |
29 | @Preview
30 | @Composable
31 | fun NamePlatePreviewDead() {
32 | CharacterDetailsNamePlateComponent(name = "Rick Sanchez", status = CharacterStatus.Dead)
33 | }
34 |
35 | @Preview
36 | @Composable
37 | fun NamePlatePreviewUnknown() {
38 | CharacterDetailsNamePlateComponent(name = "Rick Sanchez", status = CharacterStatus.Unknown)
39 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/viewmodels/AllEpisodesViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.viewmodels
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import com.androidfactory.simplerick.repositories.EpisodesRepository
6 | import com.androidfactory.simplerick.screens.AllEpisodesUiState
7 | import dagger.hilt.android.lifecycle.HiltViewModel
8 | import kotlinx.coroutines.flow.MutableStateFlow
9 | import kotlinx.coroutines.flow.asStateFlow
10 | import kotlinx.coroutines.flow.update
11 | import kotlinx.coroutines.launch
12 | import javax.inject.Inject
13 |
14 | @HiltViewModel
15 | class AllEpisodesViewModel @Inject constructor(
16 | private val repository: EpisodesRepository
17 | ) : ViewModel() {
18 |
19 | private val _uiState = MutableStateFlow(AllEpisodesUiState.Loading)
20 | val uiState = _uiState.asStateFlow()
21 |
22 | fun refreshAllEpisodes(forceRefresh: Boolean = false) = viewModelScope.launch {
23 | if (forceRefresh) _uiState.update { AllEpisodesUiState.Loading }
24 | repository.fetchAllEpisodes()
25 | .onSuccess { episodeList ->
26 | _uiState.update {
27 | AllEpisodesUiState.Success(
28 | data = episodeList.groupBy {
29 | it.seasonNumber.toString()
30 | }.mapKeys {
31 | "Season ${it.key}"
32 | }
33 | )
34 | }
35 | }.onFailure {
36 | _uiState.update { AllEpisodesUiState.Error }
37 | }
38 | }
39 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/character/CharacterStatusCircle.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.character
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.layout.Box
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.Spacer
7 | import androidx.compose.foundation.layout.height
8 | import androidx.compose.foundation.layout.size
9 | import androidx.compose.foundation.shape.CircleShape
10 | import androidx.compose.runtime.Composable
11 | import androidx.compose.ui.Alignment
12 | import androidx.compose.ui.Modifier
13 | import androidx.compose.ui.graphics.Brush
14 | import androidx.compose.ui.graphics.Color
15 | import androidx.compose.ui.tooling.preview.Preview
16 | import androidx.compose.ui.unit.dp
17 | import com.androidfactory.network.models.domain.CharacterStatus
18 | import com.androidfactory.simplerick.utils.asColor
19 |
20 | @Composable
21 | fun CharacterStatusCircle(status: CharacterStatus, modifier: Modifier = Modifier) {
22 | Box(
23 | modifier = modifier
24 | .background(
25 | brush = Brush.radialGradient(listOf(Color.Black, Color.Transparent)),
26 | shape = CircleShape
27 | )
28 | .size(20.dp),
29 | contentAlignment = Alignment.Center
30 | ) {
31 | Box(
32 | modifier = Modifier
33 | .size(8.dp)
34 | .background(color = status.asColor(), shape = CircleShape)
35 | )
36 | }
37 | }
38 |
39 | @Preview
40 | @Composable
41 | private fun CharacterStatusCirclePreview() {
42 | Column {
43 | CharacterStatusCircle(status = CharacterStatus.Alive)
44 | Spacer(modifier = Modifier.height(12.dp))
45 | CharacterStatusCircle(status = CharacterStatus.Unknown)
46 | Spacer(modifier = Modifier.height(12.dp))
47 | CharacterStatusCircle(status = CharacterStatus.Dead)
48 | }
49 | }
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/models/remote/RemoteCharacter.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network.models.remote
2 |
3 | import com.androidfactory.network.models.domain.Character
4 | import com.androidfactory.network.models.domain.CharacterGender
5 | import com.androidfactory.network.models.domain.CharacterStatus
6 | import kotlinx.serialization.Serializable
7 |
8 | @Serializable
9 | data class RemoteCharacter(
10 | val created: String,
11 | val episode: List,
12 | val gender: String,
13 | val id: Int,
14 | val image: String,
15 | val location: Location,
16 | val name: String,
17 | val origin: Origin,
18 | val species: String,
19 | val status: String,
20 | val type: String,
21 | val url: String
22 | ) {
23 | @Serializable
24 | data class Location(
25 | val name: String,
26 | val url: String
27 | )
28 |
29 | @Serializable
30 | data class Origin(
31 | val name: String,
32 | val url: String
33 | )
34 | }
35 |
36 | fun RemoteCharacter.toDomainCharacter(): Character {
37 | val characterGender = when (gender.lowercase()) {
38 | "female" -> CharacterGender.Female
39 | "male" -> CharacterGender.Male
40 | "genderless" -> CharacterGender.Genderless
41 | else -> CharacterGender.Unknown
42 | }
43 | val characterStatus = when (status.lowercase()) {
44 | "alive" -> CharacterStatus.Alive
45 | "dead" -> CharacterStatus.Dead
46 | else -> CharacterStatus.Unknown
47 | }
48 | return Character(
49 | created = created,
50 | episodeIds = episode.map { it.substring(it.lastIndexOf("/") + 1).toInt() },
51 | gender = characterGender,
52 | id = id,
53 | imageUrl = image,
54 | location = Character.Location(name = location.name, url = location.url),
55 | name = name,
56 | origin = Character.Origin(name = origin.name, url = origin.url),
57 | species = species,
58 | status = characterStatus,
59 | type = type
60 | )
61 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/character/CharacterStatusComponent.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.character
2 |
3 | import androidx.compose.foundation.border
4 | import androidx.compose.foundation.layout.Row
5 | import androidx.compose.foundation.layout.padding
6 | import androidx.compose.foundation.shape.RoundedCornerShape
7 | import androidx.compose.material3.Text
8 | import androidx.compose.runtime.Composable
9 | import androidx.compose.ui.Alignment
10 | import androidx.compose.ui.Modifier
11 | import androidx.compose.ui.tooling.preview.Preview
12 | import androidx.compose.ui.unit.dp
13 | import androidx.compose.ui.unit.sp
14 | import com.androidfactory.network.models.domain.CharacterStatus
15 | import com.androidfactory.simplerick.ui.theme.RickTextPrimary
16 | import com.androidfactory.simplerick.ui.theme.SimpleRickTheme
17 | import com.androidfactory.simplerick.utils.asColor
18 |
19 | @Composable
20 | fun CharacterStatusComponent(characterStatus: CharacterStatus) {
21 | Row(
22 | verticalAlignment = Alignment.CenterVertically,
23 | modifier = Modifier
24 | .border(
25 | width = 1.dp,
26 | color = characterStatus.asColor(),
27 | shape = RoundedCornerShape(12.dp)
28 | )
29 | .padding(horizontal = 12.dp, vertical = 4.dp)
30 | ) {
31 | Text(
32 | text = "Status: ${characterStatus.displayName}",
33 | fontSize = 20.sp,
34 | color = RickTextPrimary
35 | )
36 | }
37 | }
38 |
39 | @Preview
40 | @Composable
41 | fun CharacterStatusComponentPreviewAlive() {
42 | SimpleRickTheme {
43 | CharacterStatusComponent(characterStatus = CharacterStatus.Alive)
44 | }
45 | }
46 |
47 | @Preview
48 | @Composable
49 | fun CharacterStatusComponentPreviewDead() {
50 | SimpleRickTheme {
51 | CharacterStatusComponent(characterStatus = CharacterStatus.Dead)
52 | }
53 | }
54 |
55 | @Preview
56 | @Composable
57 | fun CharacterStatusComponentPreviewUnknown() {
58 | SimpleRickTheme {
59 | CharacterStatusComponent(characterStatus = CharacterStatus.Unknown)
60 | }
61 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/viewmodels/HomeScreenViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.viewmodels
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import com.androidfactory.network.models.domain.CharacterPage
6 | import com.androidfactory.simplerick.repositories.CharacterRepository
7 | import com.androidfactory.simplerick.screens.HomeScreenViewState
8 | import dagger.hilt.android.lifecycle.HiltViewModel
9 | import kotlinx.coroutines.flow.MutableStateFlow
10 | import kotlinx.coroutines.flow.StateFlow
11 | import kotlinx.coroutines.flow.asStateFlow
12 | import kotlinx.coroutines.flow.update
13 | import kotlinx.coroutines.launch
14 | import javax.inject.Inject
15 |
16 | @HiltViewModel
17 | class HomeScreenViewModel @Inject constructor(
18 | private val characterRepository: CharacterRepository
19 | ) : ViewModel() {
20 | private val _viewState = MutableStateFlow(HomeScreenViewState.Loading)
21 | val viewState: StateFlow = _viewState.asStateFlow()
22 |
23 | private val fetchedCharacterPages = mutableListOf()
24 |
25 | fun fetchInitialPage() = viewModelScope.launch {
26 | if (fetchedCharacterPages.isNotEmpty()) return@launch
27 | val initialPage = characterRepository.fetchCharacterPage(page = 1)
28 | initialPage.onSuccess { characterPage ->
29 | fetchedCharacterPages.clear()
30 | fetchedCharacterPages.add(characterPage)
31 |
32 | _viewState.update {
33 | return@update HomeScreenViewState.GridDisplay(characters = characterPage.characters)
34 | }
35 | }.onFailure {
36 | // todo
37 | }
38 | }
39 |
40 | fun fetchNextPage() = viewModelScope.launch {
41 | val nextPageIndex = fetchedCharacterPages.size + 1
42 | characterRepository.fetchCharacterPage(page = nextPageIndex).onSuccess { characterPage ->
43 | fetchedCharacterPages.add(characterPage)
44 | _viewState.update { currentState ->
45 | val currentCharacters = (currentState as? HomeScreenViewState.GridDisplay)?.characters ?: emptyList()
46 | return@update HomeScreenViewState.GridDisplay(characters = currentCharacters + characterPage.characters)
47 | }
48 | }.onFailure {
49 | // todo
50 | }
51 | }
52 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/viewmodels/CharacterDetailsViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.viewmodels
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import com.androidfactory.simplerick.components.common.DataPoint
6 | import com.androidfactory.simplerick.repositories.CharacterRepository
7 | import com.androidfactory.simplerick.screens.CharacterDetailsViewState
8 | import dagger.hilt.android.lifecycle.HiltViewModel
9 | import kotlinx.coroutines.flow.MutableStateFlow
10 | import kotlinx.coroutines.flow.asStateFlow
11 | import kotlinx.coroutines.flow.update
12 | import kotlinx.coroutines.launch
13 | import javax.inject.Inject
14 |
15 | @HiltViewModel
16 | class CharacterDetailsViewModel @Inject constructor(
17 | private val characterRepository: CharacterRepository
18 | ) : ViewModel() {
19 | private val _internalStorageFlow = MutableStateFlow(
20 | value = CharacterDetailsViewState.Loading
21 | )
22 | val stateFlow = _internalStorageFlow.asStateFlow()
23 |
24 | fun fetchCharacter(characterId: Int) = viewModelScope.launch {
25 | _internalStorageFlow.update { return@update CharacterDetailsViewState.Loading }
26 | characterRepository.fetchCharacter(characterId).onSuccess { character ->
27 | val dataPoints = buildList {
28 | add(DataPoint("Last known location", character.location.name))
29 | add(DataPoint("Species", character.species))
30 | add(DataPoint("Gender", character.gender.displayName))
31 | character.type.takeIf { it.isNotEmpty() }?.let { type ->
32 | add(DataPoint("Type", type))
33 | }
34 | add(DataPoint("Origin", character.origin.name))
35 | add(DataPoint("Episode count", character.episodeIds.size.toString()))
36 | }
37 | _internalStorageFlow.update {
38 | return@update CharacterDetailsViewState.Success(
39 | character = character,
40 | characterDataPoints = dataPoints
41 | )
42 | }
43 | }.onFailure { exception ->
44 | _internalStorageFlow.update {
45 | return@update CharacterDetailsViewState.Error(
46 | message = exception.message ?: "Unknown error occurred"
47 | )
48 | }
49 | }
50 | }
51 | }
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.ui.theme
2 |
3 | import android.app.Activity
4 | import android.os.Build
5 | import androidx.compose.foundation.isSystemInDarkTheme
6 | import androidx.compose.material3.MaterialTheme
7 | import androidx.compose.material3.darkColorScheme
8 | import androidx.compose.material3.dynamicDarkColorScheme
9 | import androidx.compose.material3.dynamicLightColorScheme
10 | import androidx.compose.material3.lightColorScheme
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.runtime.SideEffect
13 | import androidx.compose.ui.graphics.toArgb
14 | import androidx.compose.ui.platform.LocalContext
15 | import androidx.compose.ui.platform.LocalView
16 | import androidx.core.view.WindowCompat
17 |
18 | private val DarkColorScheme = darkColorScheme(
19 | primary = Purple80,
20 | secondary = PurpleGrey80,
21 | tertiary = Pink80
22 | )
23 |
24 | private val LightColorScheme = lightColorScheme(
25 | primary = Purple40,
26 | secondary = PurpleGrey40,
27 | tertiary = Pink40
28 |
29 | /* Other default colors to override
30 | background = Color(0xFFFFFBFE),
31 | surface = Color(0xFFFFFBFE),
32 | onPrimary = Color.White,
33 | onSecondary = Color.White,
34 | onTertiary = Color.White,
35 | onBackground = Color(0xFF1C1B1F),
36 | onSurface = Color(0xFF1C1B1F),
37 | */
38 | )
39 |
40 | @Composable
41 | fun SimpleRickTheme(
42 | darkTheme: Boolean = isSystemInDarkTheme(),
43 | // Dynamic color is available on Android 12+
44 | dynamicColor: Boolean = true,
45 | content: @Composable () -> Unit
46 | ) {
47 | val colorScheme = when {
48 | dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
49 | val context = LocalContext.current
50 | if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
51 | }
52 |
53 | darkTheme -> DarkColorScheme
54 | else -> LightColorScheme
55 | }
56 | val view = LocalView.current
57 | if (!view.isInEditMode) {
58 | SideEffect {
59 | val window = (view.context as Activity).window
60 | window.statusBarColor = RickPrimary.toArgb()
61 | WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
62 | }
63 | }
64 |
65 | MaterialTheme(
66 | colorScheme = colorScheme,
67 | typography = Typography,
68 | content = content
69 | )
70 | }
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.application)
3 | alias(libs.plugins.kotlin.android)
4 | kotlin("kapt")
5 | id("com.google.dagger.hilt.android")
6 | }
7 |
8 | android {
9 | namespace = "com.androidfactory.simplerick"
10 | compileSdk = libs.versions.compileSdk.get().toInt()
11 |
12 | defaultConfig {
13 | applicationId = "com.androidfactory.simplerick"
14 | minSdk = libs.versions.minSdk.get().toInt()
15 | targetSdk = 33
16 | versionCode = 1
17 | versionName = "1.0"
18 |
19 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
20 | vectorDrawables {
21 | useSupportLibrary = true
22 | }
23 | }
24 |
25 | buildTypes {
26 | release {
27 | isMinifyEnabled = false
28 | proguardFiles(
29 | getDefaultProguardFile("proguard-android-optimize.txt"),
30 | "proguard-rules.pro"
31 | )
32 | }
33 | }
34 | compileOptions {
35 | sourceCompatibility = JavaVersion.VERSION_17
36 | targetCompatibility = JavaVersion.VERSION_17
37 | }
38 | kotlinOptions {
39 | jvmTarget = JavaVersion.VERSION_17.toString()
40 | }
41 | buildFeatures {
42 | compose = true
43 | }
44 | composeOptions {
45 | kotlinCompilerExtensionVersion = "1.4.3"
46 | }
47 | packaging {
48 | resources {
49 | excludes += "/META-INF/{AL2.0,LGPL2.1}"
50 | }
51 | }
52 | }
53 |
54 | dependencies {
55 |
56 | implementation(project(":network"))
57 |
58 | implementation(platform(libs.compose.bom))
59 | implementation(libs.bundles.compose)
60 |
61 | implementation(libs.navigation.compose)
62 |
63 | // Image loading
64 | implementation(libs.coil.compose)
65 |
66 | // Dependency injection
67 | implementation("com.google.dagger:hilt-android:2.44")
68 | kapt("com.google.dagger:hilt-android-compiler:2.44")
69 | implementation("androidx.hilt:hilt-navigation-compose:1.2.0")
70 |
71 | implementation(libs.core.ktx)
72 | implementation(libs.lifecycle.runtime.ktx)
73 | implementation(libs.activity.compose)
74 |
75 | testImplementation(libs.junit)
76 | androidTestImplementation(libs.ext.junit)
77 | androidTestImplementation(libs.espresso.core)
78 | androidTestImplementation(platform(libs.compose.bom))
79 | androidTestImplementation(libs.compose.ui.test.junit)
80 | debugImplementation(libs.compose.ui.tooling)
81 | debugImplementation(libs.compose.ui.test.manifest)
82 | }
83 |
84 | kapt {
85 | correctErrorTypes = true
86 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | minSdk = "26"
3 | compileSdk = "34"
4 |
5 | coilComposeVersion = "2.5.0"
6 | ktorVersion = "2.3.6"
7 | agpVersion = "8.3.2"
8 | kotlinVersion = "1.8.10"
9 | composeBomVersion = "2024.09.03"
10 | navVersion = "2.7.7"
11 | activityComposeVersion = "1.9.0"
12 | coreKtxVersion = "1.13.1"
13 | lifecycleRuntimeKtxVersion = "2.8.2"
14 |
15 | espressoCoreVersion = "3.5.1"
16 | junit = "1.1.5"
17 | junitVersion = "4.13.2"
18 |
19 | [libraries]
20 | # Coil
21 | coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilComposeVersion" }
22 |
23 | # Android
24 | activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityComposeVersion" }
25 | core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtxVersion" }
26 | lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtxVersion" }
27 | navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navVersion" }
28 |
29 | # Ktor
30 | ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktorVersion" }
31 | ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktorVersion" }
32 | ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "ktorVersion" }
33 | ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktorVersion" }
34 | ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktorVersion" }
35 |
36 | # Compose
37 | compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBomVersion" }
38 | compose-ui = { module = "androidx.compose.ui:ui" }
39 | compose-ui-graphics = { module = "androidx.compose.ui:ui-graphics" }
40 | compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }
41 | compose-material3 = { module = "androidx.compose.material3:material3" }
42 | compose-foundation = { module = "androidx.compose.foundation:foundation" }
43 | compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" }
44 | compose-ui-test-junit = { module = "androidx.compose.ui:ui-test-junit4" }
45 | compose-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest" }
46 |
47 | # Testing
48 | espresso-core = { module = "androidx.test.espresso:espresso-core", version.ref = "espressoCoreVersion" }
49 | ext-junit = { module = "androidx.test.ext:junit", version.ref = "junit" }
50 | junit = { module = "junit:junit", version.ref = "junitVersion" }
51 |
52 | [plugins]
53 | android-library = { id = "com.android.library", version.ref = "agpVersion" }
54 | android-application = { id = "com.android.application", version.ref = "agpVersion" }
55 |
56 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlinVersion" }
57 | kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlinVersion" }
58 |
59 | [bundles]
60 | compose = [
61 | "compose-ui", "compose-ui-graphics", "compose-ui-tooling-preview", "compose-material3", "compose-foundation"
62 | ]
63 | ktor = [
64 | "ktor-client-core", "ktor-client-okhttp", "ktor-client-logging",
65 | "ktor-client-content-negotiation", "ktor-serialization-kotlinx-json"
66 | ]
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/character/CharacterGridItem.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.character
2 |
3 | import androidx.compose.foundation.border
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Box
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.foundation.layout.fillMaxWidth
8 | import androidx.compose.foundation.layout.padding
9 | import androidx.compose.foundation.shape.RoundedCornerShape
10 | import androidx.compose.material3.Text
11 | import androidx.compose.runtime.Composable
12 | import androidx.compose.ui.Modifier
13 | import androidx.compose.ui.draw.clip
14 | import androidx.compose.ui.graphics.Brush
15 | import androidx.compose.ui.graphics.Color
16 | import androidx.compose.ui.text.font.FontWeight
17 | import androidx.compose.ui.tooling.preview.Preview
18 | import androidx.compose.ui.unit.dp
19 | import androidx.compose.ui.unit.sp
20 | import com.androidfactory.network.models.domain.Character
21 | import com.androidfactory.network.models.domain.CharacterGender
22 | import com.androidfactory.network.models.domain.CharacterStatus
23 | import com.androidfactory.simplerick.components.common.CharacterImage
24 | import com.androidfactory.simplerick.ui.theme.RickAction
25 |
26 | @Composable
27 | fun CharacterGridItem(
28 | modifier: Modifier,
29 | character: Character,
30 | onClick: () -> Unit
31 | ) {
32 | Column(
33 | modifier = modifier
34 | .border(
35 | width = 1.dp,
36 | brush = Brush.verticalGradient(listOf(Color.Transparent, RickAction)),
37 | shape = RoundedCornerShape(12.dp)
38 | )
39 | .clip(RoundedCornerShape(12.dp))
40 | .clickable { onClick() }
41 | ) {
42 | Box {
43 | CharacterImage(imageUrl = character.imageUrl)
44 | CharacterStatusCircle(
45 | status = character.status,
46 | modifier = Modifier.padding(start = 6.dp, top = 6.dp)
47 | )
48 | }
49 | Text(
50 | text = character.name,
51 | color = RickAction,
52 | fontWeight = FontWeight.Bold,
53 | fontSize = 26.sp,
54 | lineHeight = 26.sp,
55 | modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp)
56 | )
57 | }
58 | }
59 |
60 | @Preview
61 | @Composable
62 | private fun CharacterGridItemPreview() {
63 | CharacterGridItem(
64 | modifier = Modifier.fillMaxWidth(),
65 | character = Character(
66 | created = "timestamp",
67 | episodeIds = listOf(1, 2, 3, 4, 5),
68 | gender = CharacterGender.Male,
69 | id = 123,
70 | imageUrl = "https://rickandmortyapi.com/api/character/avatar/2.jpeg",
71 | location = Character.Location(
72 | name = "Earth",
73 | url = ""
74 | ),
75 | name = "Morty Smith",
76 | origin = Character.Origin(
77 | name = "Earth",
78 | url = ""
79 | ),
80 | species = "Human",
81 | status = CharacterStatus.Alive,
82 | type = ""
83 | ),
84 | onClick = {}
85 | )
86 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/common/SimpleToolbar.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.common
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Box
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.foundation.layout.Row
8 | import androidx.compose.foundation.layout.Spacer
9 | import androidx.compose.foundation.layout.fillMaxWidth
10 | import androidx.compose.foundation.layout.height
11 | import androidx.compose.foundation.layout.padding
12 | import androidx.compose.foundation.layout.size
13 | import androidx.compose.foundation.layout.width
14 | import androidx.compose.foundation.shape.RoundedCornerShape
15 | import androidx.compose.material3.Icon
16 | import androidx.compose.material3.Text
17 | import androidx.compose.runtime.Composable
18 | import androidx.compose.ui.Alignment
19 | import androidx.compose.ui.Modifier
20 | import androidx.compose.ui.draw.clip
21 | import androidx.compose.ui.graphics.Color
22 | import androidx.compose.ui.res.painterResource
23 | import androidx.compose.ui.text.TextStyle
24 | import androidx.compose.ui.text.font.FontWeight
25 | import androidx.compose.ui.tooling.preview.Preview
26 | import androidx.compose.ui.unit.dp
27 | import androidx.compose.ui.unit.sp
28 | import com.androidfactory.simplerick.R
29 | import com.androidfactory.simplerick.ui.theme.RickTextPrimary
30 |
31 | @Composable
32 | fun SimpleToolbar(
33 | title: String,
34 | onBackAction: (() -> Unit)? = null
35 | ) {
36 | Column {
37 | Row(
38 | verticalAlignment = Alignment.CenterVertically,
39 | modifier = Modifier.padding(vertical = 12.dp, horizontal = 16.dp)
40 | ) {
41 | if (onBackAction != null) {
42 | Box(
43 | modifier = Modifier
44 | .background(shape = RoundedCornerShape(12.dp), color = Color.Transparent)
45 | .clip(shape = RoundedCornerShape(12.dp))
46 | .clickable { onBackAction() }
47 | ) {
48 | Icon(
49 | painter = painterResource(id = R.drawable.ic_arrow_back),
50 | contentDescription = "back arrow",
51 | tint = RickTextPrimary,
52 | modifier = Modifier
53 | .align(Alignment.Center)
54 | .padding(4.dp)
55 | .size(30.dp)
56 | )
57 | }
58 | Spacer(modifier = Modifier.width(12.dp))
59 | }
60 | Text(
61 | text = title,
62 | fontSize = 30.sp,
63 | style = TextStyle(
64 | color = RickTextPrimary,
65 | fontWeight = FontWeight.Bold
66 | )
67 | )
68 | }
69 | Box(
70 | modifier = Modifier
71 | .background(color = RickTextPrimary)
72 | .fillMaxWidth()
73 | .height(1.dp)
74 | )
75 | }
76 | }
77 |
78 | @Preview
79 | @Composable
80 | private fun SimpleToolbarPreview() {
81 | Column {
82 | SimpleToolbar(title = "Title here")
83 | Spacer(modifier = Modifier.height(16.dp))
84 | SimpleToolbar(title = "Title here", onBackAction = {})
85 | }
86 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/screens/HomeScreen.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.screens
2 |
3 | import androidx.compose.foundation.layout.Arrangement
4 | import androidx.compose.foundation.layout.Column
5 | import androidx.compose.foundation.layout.PaddingValues
6 | import androidx.compose.foundation.lazy.grid.GridCells
7 | import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
8 | import androidx.compose.foundation.lazy.grid.items
9 | import androidx.compose.foundation.lazy.grid.rememberLazyGridState
10 | import androidx.compose.runtime.Composable
11 | import androidx.compose.runtime.LaunchedEffect
12 | import androidx.compose.runtime.collectAsState
13 | import androidx.compose.runtime.derivedStateOf
14 | import androidx.compose.runtime.getValue
15 | import androidx.compose.runtime.remember
16 | import androidx.compose.ui.Modifier
17 | import androidx.compose.ui.unit.dp
18 | import androidx.hilt.navigation.compose.hiltViewModel
19 | import com.androidfactory.network.models.domain.Character
20 | import com.androidfactory.simplerick.components.character.CharacterGridItem
21 | import com.androidfactory.simplerick.components.common.LoadingState
22 | import com.androidfactory.simplerick.components.common.SimpleToolbar
23 | import com.androidfactory.simplerick.viewmodels.HomeScreenViewModel
24 |
25 | sealed interface HomeScreenViewState {
26 | object Loading : HomeScreenViewState
27 | data class GridDisplay(
28 | val characters: List = emptyList()
29 | ) : HomeScreenViewState
30 | }
31 |
32 | @Composable
33 | fun HomeScreen(
34 | onCharacterSelected: (Int) -> Unit,
35 | viewModel: HomeScreenViewModel = hiltViewModel()
36 | ) {
37 | val viewState by viewModel.viewState.collectAsState()
38 |
39 | LaunchedEffect(key1 = viewModel, block = { viewModel.fetchInitialPage() })
40 |
41 | val scrollState = rememberLazyGridState()
42 | val fetchNextPage: Boolean by remember {
43 | derivedStateOf {
44 | val currentCharacterCount =
45 | (viewState as? HomeScreenViewState.GridDisplay)?.characters?.size
46 | ?: return@derivedStateOf false
47 | val lastDisplayedIndex = scrollState.layoutInfo.visibleItemsInfo.lastOrNull()?.index
48 | ?: return@derivedStateOf false
49 | return@derivedStateOf lastDisplayedIndex >= currentCharacterCount - 10
50 | }
51 | }
52 |
53 | LaunchedEffect(key1 = fetchNextPage, block = {
54 | if (fetchNextPage) viewModel.fetchNextPage()
55 | })
56 |
57 | when (val state = viewState) {
58 | HomeScreenViewState.Loading -> LoadingState()
59 | is HomeScreenViewState.GridDisplay -> {
60 | Column {
61 | SimpleToolbar(title = "All characters")
62 | LazyVerticalGrid(
63 | state = scrollState,
64 | contentPadding = PaddingValues(all = 16.dp),
65 | verticalArrangement = Arrangement.spacedBy(8.dp),
66 | horizontalArrangement = Arrangement.spacedBy(8.dp),
67 | columns = GridCells.Fixed(2),
68 | content = {
69 | items(
70 | items = state.characters,
71 | key = { it.id }
72 | ) { character ->
73 | CharacterGridItem(modifier = Modifier, character = character) {
74 | onCharacterSelected(character.id)
75 | }
76 | }
77 | })
78 | }
79 | }
80 | }
81 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/episode/EpisodeRowComponent.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.episode
2 |
3 | import androidx.compose.foundation.layout.Column
4 | import androidx.compose.foundation.layout.Row
5 | import androidx.compose.foundation.layout.Spacer
6 | import androidx.compose.foundation.layout.fillMaxWidth
7 | import androidx.compose.foundation.layout.width
8 | import androidx.compose.material3.Text
9 | import androidx.compose.runtime.Composable
10 | import androidx.compose.ui.Alignment
11 | import androidx.compose.ui.Modifier
12 | import androidx.compose.ui.text.font.FontStyle
13 | import androidx.compose.ui.text.style.TextAlign
14 | import androidx.compose.ui.tooling.preview.Preview
15 | import androidx.compose.ui.unit.dp
16 | import androidx.compose.ui.unit.sp
17 | import com.androidfactory.network.models.domain.Episode
18 | import com.androidfactory.simplerick.components.common.DataPoint
19 | import com.androidfactory.simplerick.components.common.DataPointComponent
20 | import com.androidfactory.simplerick.ui.theme.RickTextPrimary
21 |
22 | @Composable
23 | fun EpisodeRowComponent(episode: Episode) {
24 | Row(verticalAlignment = Alignment.CenterVertically) {
25 | DataPointComponent(
26 | dataPoint = DataPoint(
27 | title = "Episode",
28 | description = episode.episodeNumber.toString()
29 | )
30 | )
31 | Spacer(modifier = Modifier.width(64.dp))
32 | Column {
33 | Text(
34 | text = episode.name,
35 | fontSize = 24.sp,
36 | color = RickTextPrimary,
37 | textAlign = TextAlign.End,
38 | modifier = Modifier.fillMaxWidth()
39 | )
40 | Text(
41 | text = episode.airDate,
42 | fontSize = 16.sp,
43 | color = RickTextPrimary,
44 | fontStyle = FontStyle.Italic,
45 | textAlign = TextAlign.End,
46 | modifier = Modifier.fillMaxWidth()
47 | )
48 | }
49 | }
50 | }
51 |
52 | @Preview
53 | @Composable
54 | private fun EpisodeRowComponentPreview() {
55 | val episode = Episode(
56 | id = 28,
57 | name = "The Ricklantis Mixup",
58 | seasonNumber = 3,
59 | episodeNumber = 7,
60 | airDate = "September 10, 2017",
61 | characterIdsInEpisode = listOf(
62 | 1,
63 | 2,
64 | 4,
65 | 8,
66 | 18,
67 | 22,
68 | 27,
69 | 43,
70 | 44,
71 | 48,
72 | 56,
73 | 61,
74 | 72,
75 | 73,
76 | 74,
77 | 78,
78 | 85,
79 | 86,
80 | 118,
81 | 123,
82 | 135,
83 | 143,
84 | 165,
85 | 180,
86 | 187,
87 | 206,
88 | 220,
89 | 229,
90 | 233,
91 | 235,
92 | 267,
93 | 278,
94 | 281,
95 | 283,
96 | 284,
97 | 287,
98 | 288,
99 | 289,
100 | 291,
101 | 292,
102 | 322,
103 | 325,
104 | 328,
105 | 345,
106 | 366,
107 | 367,
108 | 392,
109 | 472,
110 | 473,
111 | 474,
112 | 475,
113 | 476,
114 | 477,
115 | 478,
116 | 479,
117 | 480,
118 | 481,
119 | 482,
120 | 483,
121 | 484,
122 | 485,
123 | 486,
124 | 487,
125 | 488,
126 | 489
127 | )
128 | )
129 |
130 | EpisodeRowComponent(episode = episode)
131 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/screens/AllEpisodesScreen.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.screens
2 |
3 | import androidx.compose.foundation.ExperimentalFoundationApi
4 | import androidx.compose.foundation.background
5 | import androidx.compose.foundation.layout.Arrangement
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.foundation.layout.PaddingValues
8 | import androidx.compose.foundation.layout.Spacer
9 | import androidx.compose.foundation.layout.fillMaxWidth
10 | import androidx.compose.foundation.layout.height
11 | import androidx.compose.foundation.layout.padding
12 | import androidx.compose.foundation.lazy.LazyColumn
13 | import androidx.compose.foundation.shape.RoundedCornerShape
14 | import androidx.compose.material3.Text
15 | import androidx.compose.runtime.Composable
16 | import androidx.compose.runtime.LaunchedEffect
17 | import androidx.compose.runtime.collectAsState
18 | import androidx.compose.runtime.getValue
19 | import androidx.compose.ui.Modifier
20 | import androidx.compose.ui.graphics.Color
21 | import androidx.compose.ui.unit.dp
22 | import androidx.compose.ui.unit.sp
23 | import androidx.hilt.navigation.compose.hiltViewModel
24 | import com.androidfactory.network.models.domain.Episode
25 | import com.androidfactory.simplerick.components.common.LoadingState
26 | import com.androidfactory.simplerick.components.common.SimpleToolbar
27 | import com.androidfactory.simplerick.components.episode.EpisodeRowComponent
28 | import com.androidfactory.simplerick.ui.theme.RickAction
29 | import com.androidfactory.simplerick.ui.theme.RickPrimary
30 | import com.androidfactory.simplerick.viewmodels.AllEpisodesViewModel
31 |
32 | @OptIn(ExperimentalFoundationApi::class)
33 | @Composable
34 | fun AllEpisodesScreen(
35 | episodesViewModel: AllEpisodesViewModel = hiltViewModel()
36 | ) {
37 | val uiState by episodesViewModel.uiState.collectAsState()
38 |
39 | LaunchedEffect(key1 = Unit) {
40 | episodesViewModel.refreshAllEpisodes()
41 | }
42 |
43 | when (val state = uiState) {
44 | AllEpisodesUiState.Error -> {
45 | // todo
46 | }
47 |
48 | AllEpisodesUiState.Loading -> LoadingState()
49 | is AllEpisodesUiState.Success -> {
50 | Column {
51 | SimpleToolbar(title = "All episodes")
52 | LazyColumn(
53 | contentPadding = PaddingValues(16.dp),
54 | verticalArrangement = Arrangement.spacedBy(16.dp)
55 | ) {
56 | state.data.forEach { mapEntry ->
57 | stickyHeader(key = mapEntry.key) {
58 | Header(
59 | seasonName = mapEntry.key,
60 | uniqueCharacterCount = mapEntry.value.flatMap {
61 | it.characterIdsInEpisode
62 | }.toSet().size
63 | )
64 | }
65 |
66 | mapEntry.value.forEach { episode ->
67 | item(key = episode.id) { EpisodeRowComponent(episode = episode) }
68 | }
69 | }
70 | }
71 | }
72 | }
73 | }
74 | }
75 |
76 | @Composable
77 | private fun Header(seasonName: String, uniqueCharacterCount: Int) {
78 | Column(
79 | modifier = Modifier
80 | .fillMaxWidth()
81 | .background(color = RickPrimary)
82 | ) {
83 | Text(text = seasonName, color = Color.White, fontSize = 32.sp)
84 | Text(
85 | text = "$uniqueCharacterCount unique characters",
86 | color = Color.White,
87 | fontSize = 22.sp
88 | )
89 | Spacer(
90 | modifier = Modifier
91 | .fillMaxWidth()
92 | .padding(top = 4.dp)
93 | .height(4.dp)
94 | .background(
95 | color = RickAction,
96 | shape = RoundedCornerShape(2.dp)
97 | )
98 | )
99 | }
100 | }
101 |
102 | sealed interface AllEpisodesUiState {
103 | object Error : AllEpisodesUiState
104 | object Loading : AllEpisodesUiState
105 | data class Success(val data: Map>) : AllEpisodesUiState
106 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/viewmodels/SearchViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.viewmodels
2 |
3 | import androidx.compose.foundation.text.input.TextFieldState
4 | import androidx.compose.runtime.snapshotFlow
5 | import androidx.lifecycle.ViewModel
6 | import androidx.lifecycle.viewModelScope
7 | import com.androidfactory.network.models.domain.Character
8 | import com.androidfactory.network.models.domain.CharacterStatus
9 | import com.androidfactory.simplerick.repositories.CharacterRepository
10 | import dagger.hilt.android.lifecycle.HiltViewModel
11 | import kotlinx.coroutines.ExperimentalCoroutinesApi
12 | import kotlinx.coroutines.FlowPreview
13 | import kotlinx.coroutines.flow.MutableStateFlow
14 | import kotlinx.coroutines.flow.SharingStarted
15 | import kotlinx.coroutines.flow.StateFlow
16 | import kotlinx.coroutines.flow.asStateFlow
17 | import kotlinx.coroutines.flow.collectLatest
18 | import kotlinx.coroutines.flow.debounce
19 | import kotlinx.coroutines.flow.mapLatest
20 | import kotlinx.coroutines.flow.stateIn
21 | import kotlinx.coroutines.flow.update
22 | import kotlinx.coroutines.launch
23 | import javax.inject.Inject
24 |
25 | @HiltViewModel
26 | class SearchViewModel @Inject constructor(
27 | private val characterRepository: CharacterRepository
28 | ) : ViewModel() {
29 | val searchTextFieldState = TextFieldState()
30 |
31 | sealed interface SearchState {
32 | object Empty : SearchState
33 | data class UserQuery(val query: String) : SearchState
34 | }
35 |
36 | sealed interface ScreenState {
37 | object Empty : ScreenState
38 | object Searching : ScreenState
39 | data class Error(val message: String) : ScreenState
40 | data class Content(
41 | val userQuery: String,
42 | val results: List,
43 | val filterState: FilterState
44 | ) : ScreenState {
45 | data class FilterState(
46 | val statuses: List,
47 | val selectedStatuses: List
48 | )
49 | }
50 | }
51 |
52 | private val _uiState = MutableStateFlow(ScreenState.Empty)
53 | val uiState = _uiState.asStateFlow()
54 |
55 | @OptIn(FlowPreview::class, ExperimentalCoroutinesApi::class)
56 | private val searchTextState: StateFlow = snapshotFlow { searchTextFieldState.text }
57 | .debounce(500)
58 | .mapLatest { if (it.isBlank()) SearchState.Empty else SearchState.UserQuery(it.toString()) }
59 | .stateIn(
60 | scope = viewModelScope,
61 | started = SharingStarted.WhileSubscribed(stopTimeoutMillis = 2000),
62 | initialValue = SearchState.Empty
63 | )
64 |
65 | fun observeUserSearch() = viewModelScope.launch {
66 | searchTextState.collectLatest { searchState ->
67 | when (searchState) {
68 | is SearchState.Empty -> _uiState.update { ScreenState.Empty }
69 | is SearchState.UserQuery -> searchAllCharacters(searchState.query)
70 | }
71 | }
72 | }
73 |
74 | fun toggleStatus(status: CharacterStatus) {
75 | _uiState.update {
76 | val currentState = (it as? ScreenState.Content) ?: return@update it
77 | val currentSelectedStatuses = currentState.filterState.selectedStatuses
78 | val newStatuses = if (currentSelectedStatuses.contains(status)) {
79 | currentSelectedStatuses - status
80 | } else {
81 | currentSelectedStatuses + status
82 | }
83 | return@update currentState.copy(
84 | filterState = currentState.filterState.copy(selectedStatuses = newStatuses)
85 | )
86 | }
87 | }
88 |
89 | private fun searchAllCharacters(query: String) = viewModelScope.launch {
90 | _uiState.update { ScreenState.Searching }
91 | characterRepository.fetchAllCharactersByName(searchQuery = query).onSuccess { characters ->
92 | val allStatuses =
93 | characters.map { it.status }.toSet().toList().sortedBy { it.displayName }
94 | _uiState.update {
95 | ScreenState.Content(
96 | userQuery = query,
97 | results = characters,
98 | filterState = ScreenState.Content.FilterState(
99 | statuses = allStatuses,
100 | selectedStatuses = allStatuses
101 | )
102 | )
103 | }
104 | }.onFailure { exception ->
105 | _uiState.update { ScreenState.Error("No search results found") }
106 | }
107 | }
108 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/components/character/CharacterListItem.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.components.character
2 |
3 | import androidx.compose.foundation.border
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Arrangement
6 | import androidx.compose.foundation.layout.Box
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.PaddingValues
9 | import androidx.compose.foundation.layout.Row
10 | import androidx.compose.foundation.layout.aspectRatio
11 | import androidx.compose.foundation.layout.height
12 | import androidx.compose.foundation.layout.padding
13 | import androidx.compose.foundation.lazy.grid.GridCells
14 | import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
15 | import androidx.compose.foundation.lazy.grid.items
16 | import androidx.compose.foundation.shape.RoundedCornerShape
17 | import androidx.compose.runtime.Composable
18 | import androidx.compose.ui.Modifier
19 | import androidx.compose.ui.draw.clip
20 | import androidx.compose.ui.graphics.Brush
21 | import androidx.compose.ui.graphics.Color
22 | import androidx.compose.ui.tooling.preview.Preview
23 | import androidx.compose.ui.unit.dp
24 | import com.androidfactory.network.models.domain.Character
25 | import com.androidfactory.network.models.domain.CharacterGender
26 | import com.androidfactory.network.models.domain.CharacterStatus
27 | import com.androidfactory.simplerick.components.common.CharacterImage
28 | import com.androidfactory.simplerick.components.common.DataPoint
29 | import com.androidfactory.simplerick.components.common.DataPointComponent
30 | import com.androidfactory.simplerick.ui.theme.RickAction
31 |
32 | @Composable
33 | fun CharacterListItem(
34 | modifier: Modifier = Modifier,
35 | character: Character,
36 | characterDataPoints: List,
37 | onClick: () -> Unit
38 | ) {
39 | Row(
40 | modifier = modifier
41 | .height(140.dp)
42 | .border(
43 | width = 1.dp,
44 | brush = Brush.horizontalGradient(listOf(Color.Transparent, RickAction)),
45 | shape = RoundedCornerShape(12.dp)
46 | )
47 | .clip(RoundedCornerShape(12.dp))
48 | .clickable { onClick() }
49 | ) {
50 | Box {
51 | CharacterImage(
52 | imageUrl = character.imageUrl,
53 | modifier = Modifier
54 | .aspectRatio(1f)
55 | .clip(RoundedCornerShape(12.dp))
56 | )
57 | CharacterStatusCircle(
58 | status = character.status,
59 | modifier = Modifier.padding(start = 6.dp, top = 6.dp)
60 | )
61 | }
62 | LazyHorizontalGrid(
63 | rows = GridCells.Fixed(2),
64 | contentPadding = PaddingValues(start = 16.dp, end = 16.dp),
65 | content = {
66 | items(
67 | items = listOf(
68 | DataPoint(
69 | title = "Name",
70 | description = character.name
71 | )
72 | ) + characterDataPoints,
73 | key = { it.hashCode() }
74 | ) { dataPoint ->
75 | Column(
76 | verticalArrangement = Arrangement.Center,
77 | modifier = Modifier.padding(end = 16.dp)
78 | ) {
79 | DataPointComponent(dataPoint = dataPoint)
80 | }
81 | }
82 | })
83 | }
84 | }
85 |
86 | private fun sanitizeDataPoint(dataPoint: DataPoint): DataPoint {
87 | val newDescription = if (dataPoint.description.length > 14) {
88 | dataPoint.description.take(12) + ".."
89 | } else {
90 | dataPoint.description
91 | }
92 | return dataPoint.copy(description = newDescription)
93 | }
94 |
95 | @Preview
96 | @Composable
97 | private fun CharacterListItemPreview() {
98 | CharacterListItem(
99 | character = Character(
100 | created = "timestamp",
101 | episodeIds = listOf(1, 2, 3, 4, 5),
102 | gender = CharacterGender.Male,
103 | id = 123,
104 | imageUrl = "https://rickandmortyapi.com/api/character/avatar/2.jpeg",
105 | location = Character.Location(
106 | name = "Earth",
107 | url = ""
108 | ),
109 | name = "Morty Smith",
110 | origin = Character.Origin(
111 | name = "Earth",
112 | url = ""
113 | ),
114 | species = "Human",
115 | status = CharacterStatus.Alive,
116 | type = ""
117 | ),
118 | characterDataPoints = listOf(
119 | DataPoint(title = "Title 1", description = "Description 1"),
120 | DataPoint(title = "Title 2", description = "Description 2"),
121 | DataPoint(title = "Title 3", description = "Description 3"),
122 | DataPoint(title = "Title 4", description = "Description 4"),
123 | DataPoint(title = "Title 5", description = "Description 5"),
124 | ),
125 | onClick = {}
126 | )
127 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/screens/CharacterDetailsScreen.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.screens
2 |
3 | import androidx.compose.foundation.border
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Column
6 | import androidx.compose.foundation.layout.PaddingValues
7 | import androidx.compose.foundation.layout.Spacer
8 | import androidx.compose.foundation.layout.fillMaxSize
9 | import androidx.compose.foundation.layout.fillMaxWidth
10 | import androidx.compose.foundation.layout.height
11 | import androidx.compose.foundation.layout.padding
12 | import androidx.compose.foundation.lazy.LazyColumn
13 | import androidx.compose.foundation.lazy.items
14 | import androidx.compose.foundation.shape.RoundedCornerShape
15 | import androidx.compose.material3.Text
16 | import androidx.compose.runtime.Composable
17 | import androidx.compose.runtime.LaunchedEffect
18 | import androidx.compose.runtime.collectAsState
19 | import androidx.compose.runtime.getValue
20 | import androidx.compose.ui.Modifier
21 | import androidx.compose.ui.draw.clip
22 | import androidx.compose.ui.text.style.TextAlign
23 | import androidx.compose.ui.unit.dp
24 | import androidx.compose.ui.unit.sp
25 | import androidx.hilt.navigation.compose.hiltViewModel
26 | import com.androidfactory.network.models.domain.Character
27 | import com.androidfactory.simplerick.components.character.CharacterDetailsNamePlateComponent
28 | import com.androidfactory.simplerick.components.common.CharacterImage
29 | import com.androidfactory.simplerick.components.common.DataPoint
30 | import com.androidfactory.simplerick.components.common.DataPointComponent
31 | import com.androidfactory.simplerick.components.common.LoadingState
32 | import com.androidfactory.simplerick.components.common.SimpleToolbar
33 | import com.androidfactory.simplerick.ui.theme.RickAction
34 | import com.androidfactory.simplerick.viewmodels.CharacterDetailsViewModel
35 |
36 | sealed interface CharacterDetailsViewState {
37 | object Loading : CharacterDetailsViewState
38 | data class Error(val message: String) : CharacterDetailsViewState
39 | data class Success(
40 | val character: Character,
41 | val characterDataPoints: List
42 | ) : CharacterDetailsViewState
43 | }
44 |
45 | @Composable
46 | fun CharacterDetailsScreen(
47 | characterId: Int,
48 | viewModel: CharacterDetailsViewModel = hiltViewModel(),
49 | onEpisodeClicked: (Int) -> Unit,
50 | onBackClicked: () -> Unit
51 | ) {
52 |
53 | LaunchedEffect(key1 = Unit, block = {
54 | viewModel.fetchCharacter(characterId)
55 | })
56 |
57 | val state by viewModel.stateFlow.collectAsState()
58 |
59 | Column {
60 | SimpleToolbar(title = "Character details", onBackAction = onBackClicked)
61 | LazyColumn(
62 | modifier = Modifier.fillMaxSize(),
63 | contentPadding = PaddingValues(all = 16.dp)
64 | ) {
65 |
66 | when (val viewState = state) {
67 | CharacterDetailsViewState.Loading -> item { LoadingState() }
68 | is CharacterDetailsViewState.Error -> {
69 | // todo
70 | }
71 |
72 | is CharacterDetailsViewState.Success -> {
73 | // Name plate
74 | item {
75 | CharacterDetailsNamePlateComponent(
76 | name = viewState.character.name,
77 | status = viewState.character.status
78 | )
79 | }
80 |
81 | item { Spacer(modifier = Modifier.height(8.dp)) }
82 |
83 | // Image
84 | item {
85 | CharacterImage(imageUrl = viewState.character.imageUrl)
86 | }
87 |
88 | // Data points
89 | items(viewState.characterDataPoints) {
90 | Spacer(modifier = Modifier.height(32.dp))
91 | DataPointComponent(dataPoint = it)
92 | }
93 |
94 | item { Spacer(modifier = Modifier.height(32.dp)) }
95 |
96 | // Button
97 | item {
98 | Text(
99 | text = "View all episodes",
100 | color = RickAction,
101 | fontSize = 18.sp,
102 | textAlign = TextAlign.Center,
103 | modifier = Modifier
104 | .padding(horizontal = 32.dp)
105 | .border(
106 | width = 1.dp,
107 | color = RickAction,
108 | shape = RoundedCornerShape(12.dp)
109 | )
110 | .clip(RoundedCornerShape(12.dp))
111 | .clickable {
112 | onEpisodeClicked(characterId)
113 | }
114 | .padding(vertical = 8.dp)
115 | .fillMaxWidth()
116 | )
117 | }
118 |
119 | item { Spacer(modifier = Modifier.height(64.dp)) }
120 | }
121 | }
122 | }
123 | }
124 | }
--------------------------------------------------------------------------------
/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/main/java/com/androidfactory/simplerick/screens/CharacterEpisodeScreen.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.screens
2 |
3 | import androidx.compose.foundation.ExperimentalFoundationApi
4 | import androidx.compose.foundation.background
5 | import androidx.compose.foundation.border
6 | import androidx.compose.foundation.layout.Column
7 | import androidx.compose.foundation.layout.PaddingValues
8 | import androidx.compose.foundation.layout.Row
9 | import androidx.compose.foundation.layout.Spacer
10 | import androidx.compose.foundation.layout.fillMaxWidth
11 | import androidx.compose.foundation.layout.height
12 | import androidx.compose.foundation.layout.padding
13 | import androidx.compose.foundation.layout.width
14 | import androidx.compose.foundation.lazy.LazyColumn
15 | import androidx.compose.foundation.lazy.LazyRow
16 | import androidx.compose.foundation.lazy.items
17 | import androidx.compose.foundation.shape.RoundedCornerShape
18 | import androidx.compose.material3.Text
19 | import androidx.compose.runtime.Composable
20 | import androidx.compose.runtime.LaunchedEffect
21 | import androidx.compose.runtime.getValue
22 | import androidx.compose.runtime.mutableStateOf
23 | import androidx.compose.runtime.remember
24 | import androidx.compose.runtime.setValue
25 | import androidx.compose.ui.Modifier
26 | import androidx.compose.ui.graphics.Color
27 | import androidx.compose.ui.text.style.TextAlign
28 | import androidx.compose.ui.unit.dp
29 | import androidx.compose.ui.unit.sp
30 | import com.androidfactory.network.KtorClient
31 | import com.androidfactory.network.models.domain.Character
32 | import com.androidfactory.network.models.domain.Episode
33 | import com.androidfactory.simplerick.components.common.CharacterImage
34 | import com.androidfactory.simplerick.components.common.CharacterNameComponent
35 | import com.androidfactory.simplerick.components.common.DataPoint
36 | import com.androidfactory.simplerick.components.common.DataPointComponent
37 | import com.androidfactory.simplerick.components.common.LoadingState
38 | import com.androidfactory.simplerick.components.common.SimpleToolbar
39 | import com.androidfactory.simplerick.components.episode.EpisodeRowComponent
40 | import com.androidfactory.simplerick.ui.theme.RickPrimary
41 | import com.androidfactory.simplerick.ui.theme.RickTextPrimary
42 | import kotlinx.coroutines.launch
43 |
44 | sealed interface ScreenState {
45 | object Loading : ScreenState
46 | data class Success(val character: Character, val episodes: List) : ScreenState
47 | data class Error(val message: String) : ScreenState
48 | }
49 |
50 | @Composable
51 | fun CharacterEpisodeScreen(characterId: Int, ktorClient: KtorClient, onBackClicked: () -> Unit) {
52 | var screenState by remember { mutableStateOf(ScreenState.Loading) }
53 |
54 | LaunchedEffect(key1 = Unit, block = {
55 | ktorClient.getCharacter(characterId).onSuccess { character ->
56 | launch {
57 | ktorClient.getEpisodes(character.episodeIds).onSuccess { episodes ->
58 | screenState = ScreenState.Success(character, episodes)
59 | }.onFailure {
60 | screenState = ScreenState.Error(message = "Whoops, something went wrong")
61 | }
62 | }
63 | }.onFailure {
64 | screenState = ScreenState.Error(message = "Whoops, something went wrong")
65 | }
66 | })
67 |
68 | when (val state = screenState) {
69 | ScreenState.Loading -> LoadingState()
70 | is ScreenState.Error -> Text(
71 | text = state.message,
72 | color = Color.White,
73 | modifier = Modifier
74 | .fillMaxWidth()
75 | .padding(32.dp),
76 | textAlign = TextAlign.Center,
77 | fontSize = 26.sp
78 | )
79 |
80 | is ScreenState.Success -> MainScreen(
81 | character = state.character,
82 | episodes = state.episodes,
83 | onBackClicked = onBackClicked
84 | )
85 | }
86 | }
87 |
88 | @OptIn(ExperimentalFoundationApi::class)
89 | @Composable
90 | private fun MainScreen(character: Character, episodes: List, onBackClicked: () -> Unit) {
91 | val episodeBySeasonMap = episodes.groupBy { it.seasonNumber }
92 |
93 | Column {
94 | SimpleToolbar(title = "Character episodes", onBackAction = onBackClicked)
95 | LazyColumn(contentPadding = PaddingValues(all = 16.dp)) {
96 | item { CharacterNameComponent(name = character.name) }
97 | item { Spacer(modifier = Modifier.height(8.dp)) }
98 | item {
99 | LazyRow {
100 | episodeBySeasonMap.forEach { mapEntry ->
101 | val title = "Season ${mapEntry.key}"
102 | val description = "${mapEntry.value.size} ep"
103 | item {
104 | DataPointComponent(dataPoint = DataPoint(title, description))
105 | Spacer(modifier = Modifier.width(32.dp))
106 | }
107 | }
108 | }
109 | }
110 | item { Spacer(modifier = Modifier.height(16.dp)) }
111 | item { CharacterImage(imageUrl = character.imageUrl) }
112 | item { Spacer(modifier = Modifier.height(32.dp)) }
113 |
114 | episodeBySeasonMap.forEach { mapEntry ->
115 | stickyHeader { SeasonHeader(seasonNumber = mapEntry.key) }
116 | item { Spacer(modifier = Modifier.height(16.dp)) }
117 | items(mapEntry.value) { episode ->
118 | EpisodeRowComponent(episode = episode)
119 | Spacer(modifier = Modifier.height(16.dp))
120 | }
121 | }
122 | }
123 | }
124 | }
125 |
126 | @Composable
127 | private fun SeasonHeader(seasonNumber: Int) {
128 | Row(
129 | modifier = Modifier
130 | .fillMaxWidth()
131 | .background(color = RickPrimary)
132 | .padding(top = 8.dp, bottom = 16.dp)
133 | ) {
134 | Text(
135 | text = "Season $seasonNumber",
136 | color = RickTextPrimary,
137 | fontSize = 32.sp,
138 | lineHeight = 32.sp,
139 | textAlign = TextAlign.Center,
140 | modifier = Modifier
141 | .fillMaxWidth()
142 | .border(
143 | width = 1.dp,
144 | color = RickTextPrimary,
145 | shape = RoundedCornerShape(8.dp)
146 | )
147 | .padding(vertical = 4.dp)
148 | )
149 | }
150 | }
--------------------------------------------------------------------------------
/network/src/main/java/com/androidfactory/network/KtorClient.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.network
2 |
3 | import com.androidfactory.network.models.domain.Character
4 | import com.androidfactory.network.models.domain.CharacterPage
5 | import com.androidfactory.network.models.domain.Episode
6 | import com.androidfactory.network.models.domain.EpisodePage
7 | import com.androidfactory.network.models.remote.RemoteCharacter
8 | import com.androidfactory.network.models.remote.RemoteCharacterPage
9 | import com.androidfactory.network.models.remote.RemoteEpisode
10 | import com.androidfactory.network.models.remote.RemoteEpisodePage
11 | import com.androidfactory.network.models.remote.toDomainCharacter
12 | import com.androidfactory.network.models.remote.toDomainCharacterPage
13 | import com.androidfactory.network.models.remote.toDomainEpisode
14 | import com.androidfactory.network.models.remote.toDomainEpisodePage
15 | import io.ktor.client.HttpClient
16 | import io.ktor.client.call.body
17 | import io.ktor.client.engine.okhttp.OkHttp
18 | import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
19 | import io.ktor.client.plugins.defaultRequest
20 | import io.ktor.client.plugins.logging.Logger
21 | import io.ktor.client.plugins.logging.Logging
22 | import io.ktor.client.plugins.logging.SIMPLE
23 | import io.ktor.client.request.get
24 | import io.ktor.serialization.kotlinx.json.json
25 | import kotlinx.serialization.json.Json
26 |
27 | class KtorClient {
28 | private val client = HttpClient(OkHttp) {
29 | defaultRequest { url("https://rickandmortyapi.com/api/") }
30 |
31 | install(Logging) {
32 | logger = Logger.SIMPLE
33 | }
34 |
35 | install(ContentNegotiation) {
36 | json(Json {
37 | ignoreUnknownKeys = true
38 | })
39 | }
40 |
41 | expectSuccess = true
42 | }
43 |
44 | private var characterCache = mutableMapOf()
45 |
46 | suspend fun getCharacter(id: Int): ApiOperation {
47 | characterCache[id]?.let { return ApiOperation.Success(it) }
48 | return safeApiCall {
49 | client.get("character/$id")
50 | .body()
51 | .toDomainCharacter()
52 | .also { characterCache[id] = it }
53 | }
54 | }
55 |
56 | suspend fun getCharacterByPage(
57 | pageNumber: Int,
58 | queryParams: Map
59 | ): ApiOperation {
60 | return safeApiCall {
61 | client.get("character") {
62 | url {
63 | parameters.append("page", pageNumber.toString())
64 | queryParams.forEach { parameters.append(it.key, it.value) }
65 | }
66 | }
67 | .body()
68 | .toDomainCharacterPage()
69 | }
70 | }
71 |
72 | suspend fun searchAllCharactersByName(searchQuery: String): ApiOperation> {
73 | val data = mutableListOf()
74 | var exception: Exception? = null
75 |
76 | getCharacterByPage(
77 | pageNumber = 1,
78 | queryParams = mapOf("name" to searchQuery)
79 | ).onSuccess { firstPage ->
80 | val totalPageCount = firstPage.info.pages
81 | data.addAll(firstPage.characters)
82 |
83 | repeat(totalPageCount - 1) { index ->
84 | getCharacterByPage(
85 | pageNumber = index + 2,
86 | queryParams = mapOf("name" to searchQuery)
87 | ).onSuccess { nextPage ->
88 | data.addAll(nextPage.characters)
89 | }.onFailure { error ->
90 | exception = error
91 | }
92 |
93 | if (exception != null) { return@onSuccess }
94 | }
95 | }.onFailure {
96 | exception = it
97 | }
98 |
99 | return exception?.let { ApiOperation.Failure(it) } ?: ApiOperation.Success(data)
100 | }
101 |
102 | suspend fun getEpisode(episodeId: Int): ApiOperation {
103 | return safeApiCall {
104 | client.get("episode/$episodeId")
105 | .body()
106 | .toDomainEpisode()
107 | }
108 | }
109 |
110 | suspend fun getEpisodes(episodeIds: List): ApiOperation> {
111 | return if (episodeIds.size == 1) {
112 | getEpisode(episodeIds[0]).mapSuccess {
113 | listOf(it)
114 | }
115 | } else {
116 | val idsCommaSeparated = episodeIds.joinToString(separator = ",")
117 | safeApiCall {
118 | client.get("episode/$idsCommaSeparated")
119 | .body>()
120 | .map { it.toDomainEpisode() }
121 | }
122 | }
123 | }
124 |
125 | suspend fun getEpisodesByPage(pageIndex: Int): ApiOperation {
126 | return safeApiCall {
127 | client.get("episode") {
128 | url {
129 | parameters.append("page", pageIndex.toString())
130 | }
131 | }
132 | .body()
133 | .toDomainEpisodePage()
134 | }
135 | }
136 |
137 | suspend fun getAllEpisodes(): ApiOperation> {
138 | val data = mutableListOf()
139 | var exception: Exception? = null
140 |
141 | getEpisodesByPage(pageIndex = 1).onSuccess { firstPage ->
142 | val totalPageCount = firstPage.info.pages
143 | data.addAll(firstPage.episodes)
144 |
145 | repeat(totalPageCount - 1) { index ->
146 | getEpisodesByPage(pageIndex = index + 2).onSuccess { nextPage ->
147 | data.addAll(nextPage.episodes)
148 | }.onFailure { error ->
149 | exception = error
150 | }
151 |
152 | if (exception != null) { return@onSuccess }
153 | }
154 | }.onFailure {
155 | exception = it
156 | }
157 |
158 | return exception?.let { ApiOperation.Failure(it) } ?: ApiOperation.Success(data)
159 | }
160 |
161 | private inline fun safeApiCall(apiCall: () -> T): ApiOperation {
162 | return try {
163 | ApiOperation.Success(data = apiCall())
164 | } catch (e: Exception) {
165 | ApiOperation.Failure(exception = e)
166 | }
167 | }
168 | }
169 |
170 | sealed interface ApiOperation {
171 | data class Success(val data: T) : ApiOperation
172 | data class Failure(val exception: Exception) : ApiOperation
173 |
174 | fun mapSuccess(transform: (T) -> R): ApiOperation {
175 | return when (this) {
176 | is Success -> Success(transform(data))
177 | is Failure -> Failure(exception)
178 | }
179 | }
180 |
181 | suspend fun onSuccess(block: suspend (T) -> Unit): ApiOperation {
182 | if (this is Success) block(data)
183 | return this
184 | }
185 |
186 | fun onFailure(block: (Exception) -> Unit): ApiOperation {
187 | if (this is Failure) block(exception)
188 | return this
189 | }
190 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick
2 |
3 | import android.os.Bundle
4 | import androidx.activity.ComponentActivity
5 | import androidx.activity.compose.setContent
6 | import androidx.compose.foundation.background
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.PaddingValues
9 | import androidx.compose.foundation.layout.fillMaxSize
10 | import androidx.compose.foundation.layout.padding
11 | import androidx.compose.material.icons.Icons
12 | import androidx.compose.material.icons.filled.Home
13 | import androidx.compose.material.icons.filled.PlayArrow
14 | import androidx.compose.material.icons.filled.Search
15 | import androidx.compose.material3.Icon
16 | import androidx.compose.material3.NavigationBar
17 | import androidx.compose.material3.NavigationBarItem
18 | import androidx.compose.material3.NavigationBarItemDefaults
19 | import androidx.compose.material3.Scaffold
20 | import androidx.compose.material3.Text
21 | import androidx.compose.runtime.Composable
22 | import androidx.compose.runtime.getValue
23 | import androidx.compose.runtime.mutableIntStateOf
24 | import androidx.compose.runtime.remember
25 | import androidx.compose.runtime.setValue
26 | import androidx.compose.ui.Modifier
27 | import androidx.compose.ui.graphics.Color
28 | import androidx.compose.ui.graphics.vector.ImageVector
29 | import androidx.navigation.NavGraph.Companion.findStartDestination
30 | import androidx.navigation.NavHostController
31 | import androidx.navigation.NavType
32 | import androidx.navigation.compose.NavHost
33 | import androidx.navigation.compose.composable
34 | import androidx.navigation.compose.rememberNavController
35 | import androidx.navigation.navArgument
36 | import com.androidfactory.network.KtorClient
37 | import com.androidfactory.simplerick.screens.AllEpisodesScreen
38 | import com.androidfactory.simplerick.screens.CharacterDetailsScreen
39 | import com.androidfactory.simplerick.screens.CharacterEpisodeScreen
40 | import com.androidfactory.simplerick.screens.HomeScreen
41 | import com.androidfactory.simplerick.screens.SearchScreen
42 | import com.androidfactory.simplerick.ui.theme.RickAction
43 | import com.androidfactory.simplerick.ui.theme.RickPrimary
44 | import com.androidfactory.simplerick.ui.theme.SimpleRickTheme
45 | import dagger.hilt.android.AndroidEntryPoint
46 | import javax.inject.Inject
47 |
48 | sealed class NavDestination(val title: String, val route: String, val icon: ImageVector) {
49 | object Home : NavDestination(title = "Home", route = "home_screen", icon = Icons.Filled.Home)
50 | object Episodes :
51 | NavDestination(title = "Episodes", route = "episodes", icon = Icons.Filled.PlayArrow)
52 |
53 | object Search : NavDestination(title = "Search", route = "search", icon = Icons.Filled.Search)
54 | }
55 |
56 | @AndroidEntryPoint
57 | class MainActivity : ComponentActivity() {
58 |
59 | @Inject
60 | lateinit var ktorClient: KtorClient
61 |
62 | override fun onCreate(savedInstanceState: Bundle?) {
63 | super.onCreate(savedInstanceState)
64 | setContent {
65 |
66 | val navController = rememberNavController()
67 | val items = listOf(
68 | NavDestination.Home, NavDestination.Episodes, NavDestination.Search
69 | )
70 | var selectedIndex by remember { mutableIntStateOf(0) }
71 |
72 | SimpleRickTheme {
73 | Scaffold(
74 | bottomBar = {
75 | NavigationBar(
76 | containerColor = RickPrimary
77 | ) {
78 | items.forEachIndexed { index, screen ->
79 | NavigationBarItem(
80 | icon = {
81 | Icon(imageVector = screen.icon, contentDescription = null)
82 | },
83 | label = { Text(screen.title) },
84 | selected = index == selectedIndex,
85 | onClick = {
86 | selectedIndex = index
87 | navController.navigate(screen.route) {
88 | // Pop up to the start destination of the graph to
89 | // avoid building up a large stack of destinations
90 | // on the back stack as users select items
91 | popUpTo(navController.graph.findStartDestination().id) {
92 | saveState = true
93 | }
94 | // Avoid multiple copies of the same destination when
95 | // reselecting the same item
96 | launchSingleTop = true
97 | // Restore state when reselecting a previously selected item
98 | restoreState = true
99 | }
100 | },
101 | colors = NavigationBarItemDefaults.colors(
102 | selectedIconColor = RickAction,
103 | selectedTextColor = RickAction,
104 | indicatorColor = Color.Transparent
105 | )
106 | )
107 | }
108 | }
109 | }
110 | ) { innerPadding ->
111 | NavigationHost(
112 | navController = navController,
113 | ktorClient = ktorClient,
114 | innerPadding = innerPadding
115 | )
116 | }
117 | }
118 | }
119 | }
120 |
121 | @Composable
122 | private fun NavigationHost(
123 | navController: NavHostController,
124 | ktorClient: KtorClient,
125 | innerPadding: PaddingValues
126 | ) {
127 | NavHost(
128 | navController = navController,
129 | startDestination = "home_screen",
130 | modifier = Modifier
131 | .background(color = RickPrimary)
132 | .padding(innerPadding)
133 | ) {
134 | composable(route = "home_screen") {
135 | HomeScreen(
136 | onCharacterSelected = { characterId ->
137 | navController.navigate("character_details/$characterId")
138 | }
139 | )
140 | }
141 | composable(
142 | route = "character_details/{characterId}",
143 | arguments = listOf(navArgument("characterId") {
144 | type = NavType.IntType
145 | })
146 | ) { backStackEntry ->
147 | val characterId: Int =
148 | backStackEntry.arguments?.getInt("characterId") ?: -1
149 | CharacterDetailsScreen(
150 | characterId = characterId,
151 | onEpisodeClicked = { navController.navigate("character_episodes/$it") },
152 | onBackClicked = { navController.navigateUp() }
153 | )
154 | }
155 | composable(
156 | route = "character_episodes/{characterId}",
157 | arguments = listOf(navArgument("characterId") {
158 | type = NavType.IntType
159 | })
160 | ) { backStackEntry ->
161 | val characterId: Int =
162 | backStackEntry.arguments?.getInt("characterId") ?: -1
163 | CharacterEpisodeScreen(
164 | characterId = characterId,
165 | ktorClient = ktorClient,
166 | onBackClicked = { navController.navigateUp() }
167 | )
168 | }
169 | composable(route = NavDestination.Episodes.route) {
170 | Column(
171 | modifier = Modifier.fillMaxSize(),
172 | ) {
173 | AllEpisodesScreen()
174 | }
175 | }
176 | composable(route = NavDestination.Search.route) {
177 | SearchScreen(
178 | onCharacterClicked = { characterId ->
179 | navController.navigate("character_details/$characterId")
180 | }
181 | )
182 | }
183 | }
184 | }
185 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/androidfactory/simplerick/screens/SearchScreen.kt:
--------------------------------------------------------------------------------
1 | package com.androidfactory.simplerick.screens
2 |
3 | import androidx.compose.animation.AnimatedVisibility
4 | import androidx.compose.foundation.background
5 | import androidx.compose.foundation.border
6 | import androidx.compose.foundation.clickable
7 | import androidx.compose.foundation.layout.Arrangement
8 | import androidx.compose.foundation.layout.Box
9 | import androidx.compose.foundation.layout.Column
10 | import androidx.compose.foundation.layout.PaddingValues
11 | import androidx.compose.foundation.layout.Row
12 | import androidx.compose.foundation.layout.Spacer
13 | import androidx.compose.foundation.layout.fillMaxSize
14 | import androidx.compose.foundation.layout.fillMaxWidth
15 | import androidx.compose.foundation.layout.height
16 | import androidx.compose.foundation.layout.padding
17 | import androidx.compose.foundation.lazy.LazyColumn
18 | import androidx.compose.foundation.lazy.items
19 | import androidx.compose.foundation.shape.RoundedCornerShape
20 | import androidx.compose.foundation.text.BasicTextField
21 | import androidx.compose.foundation.text.input.clearText
22 | import androidx.compose.foundation.text.input.delete
23 | import androidx.compose.material.icons.Icons
24 | import androidx.compose.material.icons.rounded.Delete
25 | import androidx.compose.material.icons.rounded.Search
26 | import androidx.compose.material3.Button
27 | import androidx.compose.material3.ButtonDefaults
28 | import androidx.compose.material3.Icon
29 | import androidx.compose.material3.LinearProgressIndicator
30 | import androidx.compose.material3.Text
31 | import androidx.compose.runtime.Composable
32 | import androidx.compose.runtime.DisposableEffect
33 | import androidx.compose.runtime.getValue
34 | import androidx.compose.ui.Alignment
35 | import androidx.compose.ui.Modifier
36 | import androidx.compose.ui.draw.clip
37 | import androidx.compose.ui.draw.clipToBounds
38 | import androidx.compose.ui.graphics.Brush
39 | import androidx.compose.ui.graphics.Color
40 | import androidx.compose.ui.text.style.TextAlign
41 | import androidx.compose.ui.unit.dp
42 | import androidx.compose.ui.unit.sp
43 | import androidx.hilt.navigation.compose.hiltViewModel
44 | import androidx.lifecycle.compose.collectAsStateWithLifecycle
45 | import com.androidfactory.network.models.domain.CharacterStatus
46 | import com.androidfactory.simplerick.components.character.CharacterListItem
47 | import com.androidfactory.simplerick.components.common.DataPoint
48 | import com.androidfactory.simplerick.components.common.SimpleToolbar
49 | import com.androidfactory.simplerick.ui.theme.RickAction
50 | import com.androidfactory.simplerick.ui.theme.RickPrimary
51 | import com.androidfactory.simplerick.viewmodels.SearchViewModel
52 |
53 | @Composable
54 | fun SearchScreen(
55 | onCharacterClicked: (Int) -> Unit,
56 | searchViewModel: SearchViewModel = hiltViewModel()
57 | ) {
58 |
59 | DisposableEffect(key1 = Unit) {
60 | val job = searchViewModel.observeUserSearch()
61 | onDispose { job.cancel() }
62 | }
63 |
64 | Column(
65 | modifier = Modifier.fillMaxSize()
66 | ) {
67 | SimpleToolbar(title = "Search")
68 |
69 | val screenState by searchViewModel.uiState.collectAsStateWithLifecycle()
70 |
71 | AnimatedVisibility(visible = screenState is SearchViewModel.ScreenState.Searching) {
72 | LinearProgressIndicator(
73 | modifier = Modifier
74 | .height(4.dp)
75 | .fillMaxWidth(),
76 | color = RickAction
77 | )
78 | }
79 |
80 | Row(
81 | modifier = Modifier
82 | .fillMaxWidth()
83 | .padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp),
84 | verticalAlignment = Alignment.CenterVertically,
85 | horizontalArrangement = Arrangement.spacedBy(8.dp)
86 | ) {
87 | Row(
88 | modifier = Modifier
89 | .weight(1f)
90 | .background(color = Color.White, shape = RoundedCornerShape(4.dp))
91 | .padding(8.dp),
92 | verticalAlignment = Alignment.CenterVertically,
93 | horizontalArrangement = Arrangement.spacedBy(8.dp)
94 | ) {
95 | Icon(
96 | imageVector = Icons.Rounded.Search,
97 | contentDescription = "Search icon",
98 | tint = RickPrimary
99 | )
100 | BasicTextField(
101 | state = searchViewModel.searchTextFieldState,
102 | modifier = Modifier.weight(1f)
103 | )
104 | }
105 | AnimatedVisibility(visible = searchViewModel.searchTextFieldState.text.isNotBlank()) {
106 | Icon(
107 | imageVector = Icons.Rounded.Delete,
108 | contentDescription = "Delete icon",
109 | tint = RickAction,
110 | modifier = Modifier.clickable {
111 | searchViewModel.searchTextFieldState.edit { delete(0, length) }
112 | }
113 | )
114 | }
115 | }
116 |
117 | when (val state = screenState) {
118 | SearchViewModel.ScreenState.Empty -> {
119 | Text(
120 | text = "Search for characters!",
121 | color = Color.White,
122 | modifier = Modifier
123 | .fillMaxWidth()
124 | .padding(32.dp),
125 | textAlign = TextAlign.Center,
126 | fontSize = 26.sp
127 | )
128 | }
129 |
130 | SearchViewModel.ScreenState.Searching -> {}
131 | is SearchViewModel.ScreenState.Error -> {
132 | Text(
133 | text = state.message,
134 | color = Color.White,
135 | modifier = Modifier
136 | .fillMaxWidth()
137 | .padding(32.dp),
138 | textAlign = TextAlign.Center,
139 | fontSize = 26.sp
140 | )
141 |
142 | Button(
143 | colors = ButtonDefaults.buttonColors().copy(containerColor = RickAction),
144 | modifier = Modifier
145 | .fillMaxWidth()
146 | .padding(horizontal = 84.dp),
147 | onClick = { searchViewModel.searchTextFieldState.clearText() }
148 | ) {
149 | Text(text = "Clear search", color = RickPrimary)
150 | }
151 | }
152 |
153 | is SearchViewModel.ScreenState.Content -> SearchScreenContent(
154 | content = state,
155 | onStatusClicked = searchViewModel::toggleStatus,
156 | onCharacterClicked = { onCharacterClicked(it) }
157 | )
158 | }
159 | }
160 | }
161 |
162 | @Composable
163 | private fun SearchScreenContent(
164 | content: SearchViewModel.ScreenState.Content,
165 | onStatusClicked: (CharacterStatus) -> Unit,
166 | onCharacterClicked: (Int) -> Unit
167 | ) {
168 | Text(
169 | text = "${content.results.size} results for '${content.userQuery}'",
170 | color = Color.White,
171 | modifier = Modifier.padding(start = 16.dp, bottom = 4.dp),
172 | fontSize = 14.sp
173 | )
174 |
175 | StatusFilterRow(content, onStatusClicked)
176 |
177 | Box {
178 | LazyColumn(
179 | verticalArrangement = Arrangement.spacedBy(8.dp),
180 | contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 24.dp, top = 8.dp),
181 | modifier = Modifier.clipToBounds()
182 | ) {
183 | val filteredResults = content.results.filter { character ->
184 | content.filterState.selectedStatuses.contains(character.status)
185 | }
186 | items(
187 | items = filteredResults,
188 | key = { character -> character.id }
189 | ) { character ->
190 | val dataPoints = buildList {
191 | add(DataPoint("Last known location", character.location.name))
192 | add(DataPoint("Species", character.species))
193 | add(DataPoint("Gender", character.gender.displayName))
194 | character.type.takeIf { it.isNotEmpty() }?.let { type ->
195 | add(DataPoint("Type", type))
196 | }
197 | add(DataPoint("Origin", character.origin.name))
198 | add(DataPoint("Episode count", character.episodeIds.size.toString()))
199 | }
200 | CharacterListItem(
201 | character = character,
202 | characterDataPoints = dataPoints,
203 | onClick = { onCharacterClicked(character.id) },
204 | modifier = Modifier.animateItem()
205 | )
206 | }
207 | }
208 | Spacer(
209 | modifier = Modifier
210 | .height(8.dp)
211 | .fillMaxWidth()
212 | .background(
213 | brush = Brush.verticalGradient(colors = listOf(RickPrimary, Color.Transparent))
214 | )
215 | )
216 | }
217 | }
218 |
219 | @Composable
220 | private fun StatusFilterRow(
221 | content: SearchViewModel.ScreenState.Content,
222 | onStatusClicked: (CharacterStatus) -> Unit
223 | ) {
224 | Row(
225 | modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 4.dp),
226 | horizontalArrangement = Arrangement.spacedBy(12.dp)
227 | ) {
228 | content.filterState.statuses.forEach { status ->
229 | val isSelected = content.filterState.selectedStatuses.contains(status)
230 | val contentColor = if (isSelected) RickAction else Color.LightGray
231 | val count = content.results.filter { it.status == status }.size
232 | Row(
233 | modifier = Modifier
234 | .border(
235 | width = 1.dp,
236 | color = contentColor,
237 | shape = RoundedCornerShape(8.dp)
238 | )
239 | .clickable {
240 | onStatusClicked(status)
241 | }
242 | .clip(RoundedCornerShape(8.dp)),
243 | verticalAlignment = Alignment.CenterVertically
244 | ) {
245 | Text(
246 | text = count.toString(),
247 | color = RickPrimary,
248 | modifier = Modifier
249 | .background(color = contentColor)
250 | .padding(4.dp),
251 | textAlign = TextAlign.Center
252 | )
253 | Text(
254 | text = status.displayName,
255 | color = contentColor,
256 | modifier = Modifier.padding(horizontal = 6.dp),
257 | textAlign = TextAlign.Center,
258 | )
259 | }
260 | }
261 | }
262 | }
--------------------------------------------------------------------------------