Repository: kaushikgopal/movies-usf Branch: master Commit: 196b82606af2 Files: 58 Total size: 121.4 KB Directory structure: gitextract_gbcdwt71/ ├── .gitignore ├── .idea/ │ ├── .name │ └── vcs.xml ├── LICENSE ├── README.md ├── app/ │ ├── build.gradle.kts │ ├── proguard-rules.pro │ └── src/ │ ├── debug/ │ │ └── java/ │ │ └── co/ │ │ └── kaush/ │ │ └── msusf/ │ │ └── movies/ │ │ ├── OpenClass.kt │ │ └── OpenClassOnDebug.kt │ ├── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ └── co/ │ │ │ └── kaush/ │ │ │ └── msusf/ │ │ │ ├── MSApp.kt │ │ │ ├── di/ │ │ │ │ ├── AppScope.kt │ │ │ │ └── MSAppDI.kt │ │ │ └── movies/ │ │ │ ├── MSAnimationExt.kt │ │ │ ├── MSMovieActivity.kt │ │ │ ├── MSMovieApi.kt │ │ │ ├── MSMovieRepository.kt │ │ │ ├── MSMovieResult.kt │ │ │ ├── MSMovieSearchHistoryAdapter.kt │ │ │ ├── MSMovieViewModel.kt │ │ │ ├── MSMovieViewModelImpl.kt │ │ │ └── MSMovieViewState.kt │ │ └── res/ │ │ ├── drawable/ │ │ │ ├── ic_launcher_background.xml │ │ │ └── ms_list_divider_space.xml │ │ ├── drawable-v24/ │ │ │ └── ic_launcher_foreground.xml │ │ ├── layout/ │ │ │ ├── activity_main.xml │ │ │ └── view_movie.xml │ │ ├── mipmap-anydpi-v26/ │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ ├── values/ │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── strings.xml │ │ │ ├── styles.xml │ │ │ └── tags.xml │ │ └── xml/ │ │ └── network_security_config.xml │ └── test/ │ └── java/ │ └── co/ │ └── kaush/ │ └── msusf/ │ └── movies/ │ ├── CoroutineTestRule.kt │ ├── MSMovieViewModelTest.kt │ └── di/ │ └── TestMSAppDI.kt ├── build.gradle.kts ├── gradle/ │ ├── libs.versions.toml │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── usf/ ├── annotations/ │ ├── build.gradle.kts │ └── src/ │ └── main/ │ └── java/ │ └── co/ │ └── kaush/ │ └── msusf/ │ └── annotations/ │ └── UsfViewModel.kt ├── annotations-processors/ │ ├── build.gradle.kts │ └── src/ │ └── main/ │ ├── java/ │ │ └── co/ │ │ └── kaush/ │ │ └── msusf/ │ │ └── processors/ │ │ ├── UsfViewModelClassBuilderDefinition.kt │ │ ├── UsfViewModelFileBuilder.kt │ │ ├── UsfViewModelProcessor.kt │ │ ├── UsfViewModelProcessorProvider.kt │ │ └── UsfViewModelVisitor.kt │ └── resources/ │ └── META-INF/ │ └── services/ │ └── com.google.devtools.ksp.processing.SymbolProcessorProvider └── api/ ├── build.gradle.kts └── src/ └── main/ └── java/ └── co/ └── kaush/ └── usf/ ├── UsfViewModelImpl.kt └── UsfVm.kt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ############################################################################## ### macOS template # General .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk ############################################################################## ### Windows template # Windows thumbnail cache files Thumbs.db Thumbs.db:encryptable ehthumbs.db ehthumbs_vista.db # Dump file *.stackdump # Folder config file [Dd]esktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msix *.msm *.msp # Windows shortcuts *.lnk ############################################################################## ### Linux template *~ # temporary files which can be created if a process still has a handle open of a deleted file .fuse_hidden* # KDE directory preferences .directory # Linux trash folder which might appear on any partition or disk .Trash-* # .nfs files are created when an open file is removed but is still being accessed .nfs* ############################################################################## ### Visual Studio template # Visual studio project files *.vcxproj *.vcxproj.filters *.sln ############################################################################## ### JetBrains template # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 *.iml *.ipr *.iws misc.xml deploymentTargetDropDown.xml render.experimental.xml /.idea/* # Exclude non-user-specific stuff !.idea/.name !.idea/codeInsightSettings.xml !.idea/codeStyles/ !.idea/copyright/ !.idea/dataSources.xml !.idea/detekt.xml !.idea/encodings.xml !.idea/externalDependencies.xml !.idea/file.template.settings.xml !.idea/fileTemplates/ !.idea/icon.svg !.idea/inspectionProfiles/ !.idea/runConfigurations/ !.idea/scopes/ !.idea/vcs.xml ############################################################################## ### Kotlin template # Compiled class file *.class # Log file *.log # Package Files # *.jar *.war *.nar *.ear *.zip *.tar.gz *.rar # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* ############################################################################## ### C++ template # Compiled class file *.cxx ############################################################################## ### Gradle template .gradle .gradle/ # Note that you may need to exclude by hand other folders # named build if necessary (e.g., in src/) **/build/ !src/**/build/ # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) !gradle/wrapper/gradle-wrapper.jar # Cache of project .gradletasknamecache ############################################################################## ### Android-specific stuff # Built application files *.apk *.ap_ *.aab *.apks # Files for the Dalvik VM *.dex # Generated files bin/ gen/ obj/ # Local configuration file (sdk path, etc) local.properties # Google/Firebase secrets google-services.json # Android Studio generated files and folders captures/ .externalNativeBuild/ .cxx/ output.json # Keystore files *.jks *.keystore # Android Profiling *.hprof ############################################################################## ### Project Specific # !.idea/workspace.xml ================================================ FILE: .idea/.name ================================================ Movies USF Android ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Movie search using a unidirectional state flow pattern This is an attempt at coming up with a unidirectional state flow pattern that uses the concepts of patterns like Redux, Cycle.js, MVI etc. Many of my contemporaries have already done amazing work in this area and I've drawn a lot of lessons and learnings from their work already: * [The state of managing state with RxJava](https://jakewharton.com/the-state-of-managing-state-with-rxjava/) - [JakeWharton](https://twitter.com/JakeWharton) * [MVI patterns with Hannes Dorfmann](http://fragmentedpodcast.com/episodes/103/) - [Hannes Dorfmann](https://twitter.com/sockeqwe) * [LCE: Modeling Data Loading in RxJava](https://tech.instacart.com/lce-modeling-data-loading-in-rxjava-b798ac98d80) - [Laimonas](https://twitter.com/ThatLime) I wanted to achieve the benefits of this pattern without introducing any new libraries or a new framework. How would one familiar with an MVVM model today leverage the principles/benefits of a unidirectional state/data flow? I hope to demo those concepts with this app. ![usf_animation.gif "picture showing the USF animation"](usf_animation.gif) The app is a simple movie search app. Clicking the movie result populates a history list. While this is not an extremely complex app, it isn't a silly Hello World one either, so the hope is that it'll cover regular use cases for a basic application. I've also started meaninful test cases in the repo. ## Setting up your OMDB API KEY _We use the wonderful [OMDB api](http://www.omdbapi.com) to fetch movie information._ There are quotas on this api, so please don't use mine :) 1. Get an [api key for OMDB here](http://www.omdbapi.com/apikey.aspx) 2. Add it to you local.properties file (which shouldn't be checked in to a VCS) like so: ``` # local.properties OMDB_API_KEY="" ``` For great movie recommendations, ping me [@kau.sh](https://kau.sh) (seriously, I watch a lot of movies). I gave a talk at [MBLT}Dev 2018](https://twitter.com/mbltdev) on how I went about building this app. [Slides can be found here](https://speakerdeck.com/kaushikgopal/unidirectional-state-flow-patterns-a-refactoring-story). ## Getting Started This project now uses [ksp](https://kotlinlang.org/docs/ksp-overview.html) to reduce the boilerplate in wiring up a new feature. [This PR](https://github.com/kaushikgopal/movies-usf-android/pull/32) has the details for how this change was made. All that's needed is writing the implementation of your ViewModel so `MyFeatureViewModelImpl: UsfViewModelImpl` and adding the `@UsfViewModel` annotation. Your ViewModel boilerplate code will be auto-generated. Take a look at [MSMovieViewModelImpl](https://github.com/kaushikgopal/movies-usf-android/blob/master/app/src/main/java/co/kaush/msusf/movies/MSMovieViewModelImpl.kt) for the View Model logic and [MSMovieActivity](https://github.com/kaushikgopal/movies-usf-android/blob/master/app/src/main/java/co/kaush/msusf/movies/MSMovieActivity.kt) to see how the `viewModel` is invoked. # iOS app I gave another talk at [Mobilization IX](https://twitter.com/mobilizationpl/status/1184008559157219328?s=20) showing how we can use the same concepts on iOS too and wrote [my first iOS app to demonstrate these concepts - You can check that out here](https://github.com/kaushikgopal/movies-usf-ios). ================================================ FILE: app/build.gradle.kts ================================================ @file:Suppress("DSL_SCOPE_VIOLATION") // TODO: Remove once KTIJ-19369 is fixed (or agp 8.1) plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.android) alias(libs.plugins.kotlin.allopen) alias(libs.plugins.google.ksp) alias(libs.plugins.secrets.gradle.plugin) alias(libs.plugins.mannodermaus.junit5) } allOpen { annotation("co.kaush.msusf.movies.OpenClass") } android { namespace = "co.kaush.msusf.movies" compileSdk = libs.versions.compileSdk.get().toInt() defaultConfig { applicationId = "co.kaush.msusf" minSdk = libs.versions.minSdk.get().toInt() versionCode = libs.versions.appVersionCode.get().toInt() versionName = libs.versions.appVersionName.get() } buildFeatures { buildConfig = true viewBinding = true } buildTypes { getByName("release") { isMinifyEnabled = false proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro") } } compileOptions { // after agp 8.1.0-alpha09, this is no longer needed // https://kotlinlang.org/docs/gradle-configure-project.html#gradle-java-toolchains-support sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } } dependencies { ksp(libs.kotlin.inject.compiler) implementation(libs.kotlin.inject.runtime) ksp(project(":usf:annotations-processors")) // todo: put all usf in same module implementation(project(":usf:annotations")) implementation(project(":usf:api")) implementation(libs.kotlin.stdlib) implementation(libs.kotlinx.coroutines.android) implementation(libs.kotlinx.coroutines.core) implementation(libs.androidx.constraintlayout) // todo: move to compose implementation(libs.androidx.activity.ktx) implementation(libs.androidx.lifecycle.runtime.ktx) implementation(libs.androidx.lifecycle.viewmodel) implementation(libs.androidx.lifecycle.viewmodel.ktx) implementation(libs.androidx.lifecycle.viewmodel.savedstate) implementation(libs.androidx.swiperefreshlayout) implementation(libs.androidx.appcompat) implementation(libs.androidx.recyclerview) implementation(libs.coil) implementation(libs.flow.binding) implementation(libs.timber) // todo: remove implementation(platform(libs.square.okhttp.bom)) implementation(libs.square.okhttp) implementation(libs.square.okhttp.logging.interceptor) implementation(libs.square.retrofit.gson) implementation(libs.square.retrofit) debugImplementation(libs.square.leakcanary) releaseImplementation(libs.square.leakcanary.noop) // (Required) Writing and executing Unit Tests on the JUnit Platform testImplementation(libs.testing.junit5.api) testRuntimeOnly(libs.testing.junit5.engine) testImplementation(libs.testing.turbine) testImplementation(libs.testing.assertj.core) testImplementation(libs.mockito.core) testImplementation(libs.mockito.kotlin) testImplementation(libs.kotlinx.coroutines.test) // testImplementation(libs.atsl.runner) androidTestImplementation(libs.androidx.espresso.core) } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: app/src/debug/java/co/kaush/msusf/movies/OpenClass.kt ================================================ package co.kaush.msusf.movies @Target(AnnotationTarget.ANNOTATION_CLASS) annotation class OpenClass ================================================ FILE: app/src/debug/java/co/kaush/msusf/movies/OpenClassOnDebug.kt ================================================ package co.kaush.msusf.movies @OpenClass @Target(AnnotationTarget.CLASS) annotation class OpenClassOnDebug ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/co/kaush/msusf/MSApp.kt ================================================ package co.kaush.msusf import android.app.Application import co.kaush.msusf.di.AppComponent import co.kaush.msusf.movies.OpenClassOnDebug import timber.log.Timber @OpenClassOnDebug class MSApp : Application() { private val appComponent by lazy(LazyThreadSafetyMode.NONE) { AppComponent.from(this) } override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) } } ================================================ FILE: app/src/main/java/co/kaush/msusf/di/AppScope.kt ================================================ package co.kaush.msusf.di import me.tatarka.inject.annotations.Scope /** The application-level scope. There will only be one instance of anything annotated with this. */ @Scope annotation class AppScope ================================================ FILE: app/src/main/java/co/kaush/msusf/di/MSAppDI.kt ================================================ package co.kaush.msusf.di import android.content.Context import co.kaush.msusf.MSApp import co.kaush.msusf.movies.MSMovieApi import co.kaush.msusf.movies.MSMovieRepository import me.tatarka.inject.annotations.Component import me.tatarka.inject.annotations.Provides import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** These are components that you'll need in both Test and Prod */ abstract class CommonAppComponent { abstract val movieRepository: MSMovieRepository } @AppScope @Component abstract class AppComponent( @get:Provides val app: MSApp, ) : CommonAppComponent() { @AppScope @Provides protected fun provideRetrofit(): Retrofit { val interceptor = (HttpLoggingInterceptor()).apply { level = HttpLoggingInterceptor.Level.BODY } val okHttpClient: OkHttpClient = OkHttpClient.Builder().addNetworkInterceptor(interceptor).build() return Retrofit.Builder() .baseUrl("http://www.omdbapi.com") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build() } @AppScope @Provides fun provideMovieApi(retrofit: Retrofit): MSMovieApi { return retrofit.create(MSMovieApi::class.java) } companion object { private var instance: AppComponent? = null fun from(context: Context): AppComponent = instance ?: AppComponent::class.create(context.applicationContext as MSApp).also { instance = it } } } ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSAnimationExt.kt ================================================ package co.kaush.msusf.movies import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.animation.PropertyValuesHolder import android.view.View import android.view.animation.OvershootInterpolator import android.widget.ImageView fun ImageView.growShrink() { val expansionFactor: Float = 0.2F val growX = PropertyValuesHolder.ofFloat(View.SCALE_X, 1f + expansionFactor) val growY = PropertyValuesHolder.ofFloat(View.SCALE_Y, 1f + expansionFactor) val growAnimation = ObjectAnimator.ofPropertyValuesHolder(this, growX, growY) growAnimation.interpolator = OvershootInterpolator() val shrinkX = PropertyValuesHolder.ofFloat(View.SCALE_X, 1f) val shrinkY = PropertyValuesHolder.ofFloat(View.SCALE_Y, 1f) val shrinkAnimation = ObjectAnimator.ofPropertyValuesHolder(this, shrinkX, shrinkY) shrinkAnimation.interpolator = OvershootInterpolator() val animSetXY = AnimatorSet() animSetXY.playSequentially(growAnimation, shrinkAnimation) animSetXY.start() } ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSMovieActivity.kt ================================================ package co.kaush.msusf.movies import android.os.Bundle import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.viewModels import androidx.core.content.ContextCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL import androidx.swiperefreshlayout.widget.CircularProgressDrawable import co.kaush.msusf.di.AppComponent import co.kaush.msusf.movies.MSMovieEvent.AddToHistoryEvent import co.kaush.msusf.movies.MSMovieEvent.RestoreFromHistoryEvent import co.kaush.msusf.movies.MSMovieEvent.ScreenLoadEvent import co.kaush.msusf.movies.MSMovieEvent.SearchMovieEvent import co.kaush.msusf.movies.databinding.ActivityMainBinding import coil.load import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import reactivecircus.flowbinding.android.view.clicks import timber.log.Timber class MSMovieActivity : ComponentActivity() { private lateinit var movieRepo: MSMovieRepository private val viewModel: MSMovieViewModel by viewModels { MSMovieViewModel.MSMovieViewModelFactory(movieRepo) } private lateinit var listAdapter: MSMovieSearchHistoryAdapter private lateinit var binding: ActivityMainBinding private val historyItemClick = MutableSharedFlow() private val spinner: CircularProgressDrawable by lazy { val circularProgressDrawable = CircularProgressDrawable(this) circularProgressDrawable.strokeWidth = 5f circularProgressDrawable.centerRadius = 30f circularProgressDrawable.start() circularProgressDrawable } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val appComponent = AppComponent.from(this) movieRepo = appComponent.movieRepository setupListView() binding.longRunningTask.setOnClickListener { GlobalScope.launch(Dispatchers.Default) { viewModel.processInput(MSMovieEvent.LongRunningEvent) } } viewModel.viewState .onEach { render(it) } .catch { Timber.e(it, "error rendering view state") } .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED) .launchIn(lifecycleScope) viewModel.effects .onEach { trigger(it) } .catch { Timber.e(it, "error triggering side effect") } .flowWithLifecycle(lifecycle, Lifecycle.State.STARTED) .launchIn(lifecycleScope) } override fun onResume() { super.onResume() val screenLoadEvents = flowOf(ScreenLoadEvent) val searchMovieEvents = binding.msMainScreenSearchBtn.clicks().map { SearchMovieEvent(binding.msMainScreenSearchText.text.toString()) } val addToHistoryEvents = binding.msMainScreenPoster.clicks().map { binding.msMainScreenPoster.growShrink() AddToHistoryEvent(binding.msMainScreenPoster.getTag(R.id.TAG_MOVIE_DATA) as MSMovie) } val restoreFromHistoryEvents = historyItemClick.map { RestoreFromHistoryEvent(it) } merge( screenLoadEvents, searchMovieEvents, addToHistoryEvents, restoreFromHistoryEvents, ) .onEach { viewModel.processInput(it) } .catch { Timber.e(it, "error processing input ") } .flowWithLifecycle(lifecycle, Lifecycle.State.RESUMED) .launchIn(lifecycleScope) } private fun trigger(effect: MSMovieEffect) { Timber.d("----- [trigger] ${Thread.currentThread().name}") when (effect) { is MSMovieEffect.AddedToHistoryToastEffect -> { Toast.makeText(this, "added to history", Toast.LENGTH_SHORT).show() } } } private fun render(vs: MSMovieViewState) { Timber.d("----- [render] ${Thread.currentThread().name}") vs.searchBoxText.let { binding.msMainScreenSearchText.setText(it) } binding.msMainScreenTitle.text = vs.searchedMovieTitle binding.msMainScreenRating.text = vs.searchedMovieRating vs.searchedMoviePoster .takeIf { it.isNotBlank() } ?.let { binding.msMainScreenPoster.load(vs.searchedMoviePoster) { placeholder(spinner) } binding.msMainScreenPoster.setTag(R.id.TAG_MOVIE_DATA, vs.searchedMovieReference) } ?: run { binding.msMainScreenPoster.setImageResource(0) } listAdapter.submitList(vs.adapterList) } private fun setupListView() { val layoutManager = LinearLayoutManager(this, HORIZONTAL, false) binding.msMainScreenSearchHistory.layoutManager = layoutManager val dividerItemDecoration = DividerItemDecoration(this, HORIZONTAL) dividerItemDecoration.setDrawable( ContextCompat.getDrawable(this, R.drawable.ms_list_divider_space)!!, ) binding.msMainScreenSearchHistory.addItemDecoration(dividerItemDecoration) listAdapter = MSMovieSearchHistoryAdapter { lifecycleScope.launch { historyItemClick.emit(it) } } binding.msMainScreenSearchHistory.adapter = listAdapter } } ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSMovieApi.kt ================================================ package co.kaush.msusf.movies import com.google.gson.annotations.SerializedName import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface MSMovieApi { @GET("/") suspend fun searchMovie( @Query("t") movieName: String, @Query("apiKey") apiKey: String = BuildConfig.OMDB_API_KEY ): Response } data class MSMovie( @SerializedName("Result") val result: Boolean, @SerializedName("Error") val errorMessage: String? = null, @SerializedName("Title") val title: String = "", @SerializedName("Poster") val posterUrl: String = "", @SerializedName("Ratings") val ratings: List = emptyList() ) { val ratingSummary: String get() { return ratings.fold("") { summary, msRating -> "$summary\n${msRating.summary}" } } } data class MSRating( @SerializedName("Source") val source: String, @SerializedName("Value") val rating: String ) { val summary: String get() = "$rating (${sourceShortName(source)})" private fun sourceShortName(ratingSource: String): String { return when { ratingSource.contains("Internet Movie Database") -> "IMDB" ratingSource.contains("Rotten Tomatoes") -> "RT" ratingSource.contains("Metacritic") -> "Metac" else -> ratingSource } } } ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSMovieRepository.kt ================================================ package co.kaush.msusf.movies import co.kaush.msusf.di.AppScope import com.google.gson.Gson import me.tatarka.inject.annotations.Inject class MSMovieRepository @AppScope @Inject constructor(val movieApi: MSMovieApi) { suspend fun searchMovie(movieName: String): MSMovie? { val response = movieApi.searchMovie(movieName) response.body()?.let { return it } return response.errorBody()?.let { body -> Gson() .fromJson( body.string(), MSMovie::class.java, ) } } } ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSMovieResult.kt ================================================ package co.kaush.msusf.movies import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow sealed class MSMovieResult { abstract val loading: Boolean abstract val errorMessage: String abstract fun toViewState(currentViewState: MSMovieViewState): MSMovieViewState abstract fun toEffects(): Flow data class ScreenLoadResult( override val loading: Boolean = false, override val errorMessage: String = "", ) : MSMovieResult() { override fun toViewState(currentViewState: MSMovieViewState): MSMovieViewState = currentViewState.copy(searchBoxText = "") override fun toEffects(): Flow = emptyFlow() } data class SearchMovieResult( override val loading: Boolean = false, override val errorMessage: String = "", val movie: MSMovie? = null, ) : MSMovieResult() { override fun toViewState(currentViewState: MSMovieViewState): MSMovieViewState { val movie: MSMovie = movie!! return currentViewState.copy( searchBoxText = movie.title, searchedMovieTitle = movie.title, searchedMovieRating = movie.ratingSummary, searchedMoviePoster = movie.posterUrl, searchedMovieReference = movie, ) } override fun toEffects(): Flow = emptyFlow() } data class AddToHistoryResult( override val loading: Boolean = false, override val errorMessage: String = "", val movie: MSMovie? = null, ) : MSMovieResult() { override fun toViewState(currentViewState: MSMovieViewState): MSMovieViewState { val movie: MSMovie = movie!! return if (!currentViewState.adapterList.contains(movie)) { currentViewState.copy(adapterList = currentViewState.adapterList.plus(movie)) } else currentViewState.copy() } override fun toEffects(): Flow { return flow { emit(MSMovieEffect.AddedToHistoryToastEffect) } } } } ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSMovieSearchHistoryAdapter.kt ================================================ package co.kaush.msusf.movies import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.annotation.LayoutRes import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.CircularProgressDrawable import coil.load class MSMovieSearchHistoryAdapter(private val historyClickListener: (MSMovie) -> Unit) : ListAdapter(MSMovieSearchDiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MSMovieSearchVH { return MSMovieSearchVH(parent.inflate(R.layout.view_movie)) } override fun onBindViewHolder(holder: MSMovieSearchVH, position: Int) { holder.bind(getItem(position), historyClickListener) } } class MSMovieSearchDiffCallback : DiffUtil.ItemCallback() { // only one kind of item override fun areItemsTheSame(oldItem: MSMovie, newItem: MSMovie): Boolean = true override fun areContentsTheSame(oldItem: MSMovie, newItem: MSMovie): Boolean { // this is just lazy! return oldItem.posterUrl.equals(newItem.posterUrl, ignoreCase = true) } } class MSMovieSearchVH(itemView: View) : RecyclerView.ViewHolder(itemView) { private val posterView: ImageView = itemView.findViewById(R.id.ms_result_poster) private val ratingView: TextView = itemView.findViewById(R.id.ms_result_rating) private val spinner: CircularProgressDrawable by lazy { val circularProgressDrawable = CircularProgressDrawable(itemView.context) circularProgressDrawable.strokeWidth = 5f circularProgressDrawable.centerRadius = 30f circularProgressDrawable.start() circularProgressDrawable } @SuppressLint("SetTextI18n") fun bind(item: MSMovie, historyClickListener: (MSMovie) -> Unit) { (item.ratings.first()).let { ratingView.text = it.summary } item.posterUrl.takeIf { it.isNotBlank() }?.let { posterView.load(it) { placeholder(spinner) } } ?: run { posterView.setImageResource(0) } itemView.setOnClickListener { historyClickListener.invoke(item) posterView.growShrink() } } } // ----------------------------------------------------------------------------------- // helpers /** * Usage: `val view = container?.inflate(R.layout.activity)` * `inflater?.inflate(R.layout.fragment_dialog_standard, c)!!` */ private fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View = LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot) ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSMovieViewModel.kt ================================================ package co.kaush.msusf.movies import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider.Factory import androidx.lifecycle.viewModelScope import java.lang.Class import kotlin.Suppress import kotlin.Unit import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow public class MSMovieViewModel( movieRepo: MSMovieRepository, ) : ViewModel() { private val MSMovieViewModelImpl: MSMovieViewModelImpl = MSMovieViewModelImpl(movieRepo = movieRepo, coroutineScope = viewModelScope) public val effects: SharedFlow get() = MSMovieViewModelImpl.effects public val viewState: StateFlow get() = MSMovieViewModelImpl.viewState public fun processInput(event: MSMovieEvent): Unit = MSMovieViewModelImpl.processInput(event = event) public class MSMovieViewModelFactory( private val movieRepo: MSMovieRepository, ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") public override fun create(modelClass: Class): T = MSMovieViewModel(movieRepo = movieRepo) as T } } ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSMovieViewModelImpl.kt ================================================ package co.kaush.msusf.movies import co.kaush.msusf.movies.MSMovieEvent.LongRunningEvent import co.kaush.usf.UsfViewModelImpl import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow // @UsfViewModel class MSMovieViewModelImpl( private val movieRepo: MSMovieRepository, coroutineScope: CoroutineScope, dispatcher: CoroutineDispatcher = Dispatchers.IO, ) : UsfViewModelImpl( MSMovieViewState(), coroutineScope, dispatcher, ) { // ----------------------------------------------------------------------------------- // Event -> Results override fun eventToResultFlow(event: MSMovieEvent): Flow { return when (event) { is MSMovieEvent.ScreenLoadEvent -> onScreenLoad() is MSMovieEvent.SearchMovieEvent -> onSearchMovie(event) is MSMovieEvent.AddToHistoryEvent -> onAddToHistory(event) is MSMovieEvent.RestoreFromHistoryEvent -> onRestoreFromHistory(event) is LongRunningEvent -> onLongRunningTask(event) } } private fun onScreenLoad(): Flow = flow { emit(MSMovieResult.ScreenLoadResult()) } private fun onLongRunningTask(event: LongRunningEvent): Flow { return flow { delay(2000) emit( MSMovieResult.SearchMovieResult( movie = MSMovie( true, title = "Batman (1989)", posterUrl = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBYWFRgWFRUZGBgaGhkcHBoYGBwaGBwaGhwcHBkcGRgdIS4lHB4rIRoYJjgmKy8xNTU1GiQ7QDszPy40NTEBDAwMEA8QHxISHzQrJCs0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0NP/AABEIARMAtwMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAAAAQIDBAUGB//EAD8QAAIBAgQEAwYCCAYBBQAAAAECEQADBBIhMQVBUWEicYEGEzKRobHB8AcjQlJiotHhFHKCkrLCFUNT0vHy/8QAGAEAAwEBAAAAAAAAAAAAAAAAAAECAwT/xAAiEQEBAAICAgICAwAAAAAAAAAAAQIREiEDMUFRBGETIrH/2gAMAwEAAhEDEQA/APIaKKKZCiiigCiiigCiiKcEoLbZ4fZjCX3P7Vy0o/05mb/knyrHKaxXS27RXhqE7PinjyVLa/cNWE6anvr89fxp6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aVyzcMCP3X36azSuwgagTH8qCPvVWDEFQYnefwNPV208I027SAOvQU9p0sW7vw+af9lP8AxqLOTlImcu/PViv4/WmZyADlECI35Ekc+5otXGHwjUCJ5xM9Yo2NJCfB/L/MD/1NIWhTGoGYDyDKR/ypvvG2yjcGNd9TO/ekLkg+Ea776mR36gbUDQuOcpnfNB9Aark1NcZmnwjUkmOvPnUWQ9PyaVVDaKf7s9KQoaR9G0U4oelNoMUUUUAUUUUAUUUUAUUUUBIHJ5/anbAw32pmYfu/WkJHT60y0lDnWW+3f8+tBbX4tOulRSOh+f8AaiRyH1mgaS59YzaddKVm38f261G9yREDelW7HIc/rRsaPUgjVvt6UjED4W+1NS5AiKR7k8oo2Wkkifi+3aKar/xdxtvSG7yigXu1GxorvB0b7UgfbXp060iXI5UhcEkkfWg9JGbo3Xp6Uinq32qMkdPrQGHSgaSOx1AMjrpUNSi9AIA3qKkIKKKKDFFFFAFFFFMCiiigCiiigCiiigCiiigCiiigCiiigCiiigCiiigCiiigCiiigCiiigP/2Q==", ), ), ) } } private fun onSearchMovie(event: MSMovieEvent.SearchMovieEvent): Flow { return flow { emit(MSMovieResult.SearchMovieResult(loading = true)) try { val movie = movieRepo.searchMovie(event.searchedMovieTitle) emit( MSMovieResult.SearchMovieResult( movie = movie, errorMessage = movie?.errorMessage ?: "", ), ) } catch (e: Exception) { emit( MSMovieResult.SearchMovieResult( movie = MSMovie(result = false, errorMessage = e.localizedMessage), errorMessage = e.localizedMessage ?: "", ), ) } } } private fun onAddToHistory(event: MSMovieEvent.AddToHistoryEvent): Flow { return flow { emit(MSMovieResult.AddToHistoryResult(movie = event.searchedMovie)) } } private fun onRestoreFromHistory( event: MSMovieEvent.RestoreFromHistoryEvent ): Flow { return flow { emit(MSMovieResult.SearchMovieResult(movie = event.movieFromHistory)) } } // ----------------------------------------------------------------------------------- // Results -> ViewState override fun resultToViewState( currentViewState: MSMovieViewState, result: MSMovieResult ): MSMovieViewState { return when { result.loading -> { currentViewState.copy( searchBoxText = "", searchedMovieTitle = "Searching Movie...", searchedMovieRating = "", searchedMoviePoster = "", searchedMovieReference = null, ) } result.errorMessage.isNotBlank() -> { currentViewState.copy(searchedMovieTitle = result.errorMessage) } else -> result.toViewState(currentViewState) } } // ----------------------------------------------------------------------------------- // Results -> Effect override fun resultToEffects(result: MSMovieResult): Flow = result.toEffects() } ================================================ FILE: app/src/main/java/co/kaush/msusf/movies/MSMovieViewState.kt ================================================ package co.kaush.msusf.movies data class MSMovieViewState( val searchBoxText: String = "Blade", val searchedMovieTitle: String = "", val searchedMovieRating: String = "", val searchedMoviePoster: String = "", val searchedMovieReference: MSMovie? = null, val adapterList: List = emptyList() ) sealed class MSMovieEffect { object AddedToHistoryToastEffect : MSMovieEffect() } sealed class MSMovieEvent { object ScreenLoadEvent : MSMovieEvent() object LongRunningEvent : MSMovieEvent() data class SearchMovieEvent(val searchedMovieTitle: String = "") : MSMovieEvent() data class AddToHistoryEvent(val searchedMovie: MSMovie) : MSMovieEvent() data class RestoreFromHistoryEvent(val movieFromHistory: MSMovie) : MSMovieEvent() } ================================================ FILE: app/src/main/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ms_list_divider_space.xml ================================================ ================================================ FILE: app/src/main/res/drawable-v24/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/layout/activity_main.xml ================================================