├── .gitignore ├── .idea └── vcs.xml ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── codingwithmitch │ │ └── mviexample │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── codingwithmitch │ │ │ └── mviexample │ │ │ ├── api │ │ │ ├── ApiService.kt │ │ │ └── MyRetrofitBuilder.kt │ │ │ ├── model │ │ │ ├── BlogPost.kt │ │ │ └── User.kt │ │ │ ├── repository │ │ │ ├── NetworkBoundResource.kt │ │ │ └── Repository.kt │ │ │ ├── ui │ │ │ ├── DataStateListener.kt │ │ │ └── main │ │ │ │ ├── MainActivity.kt │ │ │ │ ├── MainFragment.kt │ │ │ │ ├── MainRecyclerAdapter.kt │ │ │ │ ├── MainViewModel.kt │ │ │ │ └── state │ │ │ │ ├── MainStateEvent.kt │ │ │ │ └── MainViewState.kt │ │ │ └── util │ │ │ ├── AbsentLiveData.kt │ │ │ ├── Constants.kt │ │ │ ├── DataState.kt │ │ │ ├── Event.kt │ │ │ ├── GenericApiResponse.kt │ │ │ ├── LiveDataCallAdapter.kt │ │ │ ├── LiveDataCallAdapterFactory.kt │ │ │ └── TopSpacingItemDecoration.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── fragment_main.xml │ │ └── layout_blog_list_item.xml │ │ ├── menu │ │ └── main_menu.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── codingwithmitch │ └── mviexample │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.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 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Example MVI implementation

2 |

This repository is code for a video course. Click here to watch the course.

3 |

The app uses the following libraries / topics:

4 | 13 |
14 |

The app does two things:

15 |
    16 |
  1. Get 'User' data from open-api.xyz/placeholder/user.
  2. 17 |
  3. Get a list of 'BlogPost' data from open-api.xyz/placeholder/blogs.
  4. 18 |
19 |
20 |

21 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | 5 | apply plugin: 'kotlin-android-extensions' 6 | 7 | apply plugin: 'kotlin-kapt' 8 | 9 | android { 10 | compileSdkVersion 28 11 | defaultConfig { 12 | applicationId "com.codingwithmitch.mviexample" 13 | minSdkVersion 21 14 | targetSdkVersion 28 15 | versionCode 1 16 | versionName "1.0" 17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 18 | } 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | } 26 | 27 | dependencies { 28 | implementation fileTree(dir: 'libs', include: ['*.jar']) 29 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 30 | implementation 'androidx.appcompat:appcompat:1.0.2' 31 | implementation 'androidx.core:core-ktx:1.0.2' 32 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 33 | implementation 'androidx.legacy:legacy-support-v4:1.0.0' 34 | testImplementation 'junit:junit:4.12' 35 | androidTestImplementation 'androidx.test:runner:1.2.0' 36 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 37 | 38 | 39 | // -- Retrofit2 40 | def retrofit2_version = "2.6.0" 41 | implementation "com.squareup.retrofit2:retrofit:$retrofit2_version" 42 | implementation "com.squareup.retrofit2:converter-gson:$retrofit2_version" 43 | 44 | // -- Lifecycle Components (ViewModel, LiveData and ReactiveStreams) 45 | def lifecycle_version = "2.2.0-alpha03" 46 | implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version" 47 | kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" 48 | 49 | // -- Coroutines 50 | def coroutines_version = "1.2.1" 51 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" 52 | implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version" 53 | 54 | // RecyclerView 55 | def recyclerview_version = "1.1.0-beta03" 56 | implementation "androidx.recyclerview:recyclerview:$recyclerview_version" 57 | 58 | def material_version = "1.1.0-alpha09" 59 | implementation "com.google.android.material:material:$material_version" 60 | 61 | //glide 62 | def glide_version = "4.9.0" 63 | implementation "com.github.bumptech.glide:glide:$glide_version" 64 | annotationProcessor "com.github.bumptech.glide:compiler:$glide_version" 65 | 66 | // Leak Canary (detecting memory leaks) 67 | def leak_canary_version = "2.0-alpha-3" 68 | debugImplementation "com.squareup.leakcanary:leakcanary-android:$leak_canary_version" 69 | } 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/codingwithmitch/mviexample/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample 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.codingwithmitch.mviexample", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/api/ApiService.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.api 2 | 3 | import androidx.lifecycle.LiveData 4 | import com.codingwithmitch.mviexample.model.BlogPost 5 | import com.codingwithmitch.mviexample.model.User 6 | import com.codingwithmitch.mviexample.util.GenericApiResponse 7 | import retrofit2.http.GET 8 | import retrofit2.http.Path 9 | 10 | interface ApiService { 11 | 12 | @GET("placeholder/blogs") 13 | fun getBlogPosts(): LiveData>> 14 | 15 | @GET("placeholder/user/{userId}") 16 | fun getUser( 17 | @Path("userId") userId: String 18 | ): LiveData> 19 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/api/MyRetrofitBuilder.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.api 2 | 3 | import com.codingwithmitch.mviexample.util.LiveDataCallAdapterFactory 4 | import retrofit2.Retrofit 5 | import retrofit2.converter.gson.GsonConverterFactory 6 | 7 | object MyRetrofitBuilder { 8 | 9 | const val BASE_URL: String = "https://open-api.xyz/" 10 | 11 | val retrofitBuilder: Retrofit.Builder by lazy { 12 | Retrofit.Builder() 13 | .baseUrl(BASE_URL) 14 | .addCallAdapterFactory(LiveDataCallAdapterFactory()) 15 | .addConverterFactory(GsonConverterFactory.create()) 16 | } 17 | 18 | 19 | val apiService: ApiService by lazy{ 20 | retrofitBuilder 21 | .build() 22 | .create(ApiService::class.java) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/model/BlogPost.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.model 2 | 3 | 4 | import com.google.gson.annotations.Expose 5 | import com.google.gson.annotations.SerializedName 6 | 7 | data class BlogPost( 8 | 9 | @Expose 10 | @SerializedName("pk") 11 | val pk: Int? = null, 12 | 13 | @Expose 14 | @SerializedName("title") 15 | val title: String? = null, 16 | 17 | @Expose 18 | @SerializedName("body") 19 | val body: String? = null, 20 | 21 | @Expose 22 | @SerializedName("image") 23 | val image: String? = null 24 | ) { 25 | override fun equals(other: Any?): Boolean { 26 | if (javaClass != other?.javaClass) return false 27 | 28 | other as BlogPost 29 | 30 | if (pk != other.pk) return false 31 | 32 | return true 33 | } 34 | 35 | override fun toString(): String { 36 | return "BlogPost(title=$title, body=$body, image=$image)" 37 | } 38 | } 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/model/User.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.model 2 | 3 | import com.google.gson.annotations.Expose 4 | import com.google.gson.annotations.SerializedName 5 | 6 | data class User( 7 | 8 | @Expose 9 | @SerializedName("email") 10 | val email: String? = null, 11 | 12 | @Expose 13 | @SerializedName("username") 14 | val username: String? = null, 15 | 16 | @Expose 17 | @SerializedName("image") 18 | val image: String? = null 19 | ) { 20 | override fun toString(): String { 21 | return "User(email=$email, username=$username, image=$image)" 22 | } 23 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/repository/NetworkBoundResource.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.repository 2 | 3 | import androidx.lifecycle.LiveData 4 | import androidx.lifecycle.MediatorLiveData 5 | import com.codingwithmitch.mviexample.util.* 6 | import com.codingwithmitch.mviexample.util.Constants.Companion.TESTING_NETWORK_DELAY 7 | import kotlinx.coroutines.Dispatchers.IO 8 | import kotlinx.coroutines.Dispatchers.Main 9 | import kotlinx.coroutines.GlobalScope 10 | import kotlinx.coroutines.delay 11 | import kotlinx.coroutines.launch 12 | import kotlinx.coroutines.withContext 13 | 14 | abstract class NetworkBoundResource { 15 | 16 | protected val result = MediatorLiveData>() 17 | 18 | init { 19 | result.value = DataState.loading(true) 20 | 21 | 22 | GlobalScope.launch(IO){ 23 | delay(TESTING_NETWORK_DELAY) 24 | 25 | withContext(Main){ 26 | val apiResponse = createCall() 27 | result.addSource(apiResponse) { response -> 28 | result.removeSource(apiResponse) 29 | 30 | handleNetworkCall(response) 31 | } 32 | } 33 | } 34 | } 35 | 36 | fun handleNetworkCall(response: GenericApiResponse){ 37 | 38 | when(response){ 39 | is ApiSuccessResponse ->{ 40 | handleApiSuccessResponse(response) 41 | } 42 | is ApiErrorResponse ->{ 43 | println("DEBUG: NetworkBoundResource: ${response.errorMessage}") 44 | onReturnError(response.errorMessage) 45 | } 46 | is ApiEmptyResponse ->{ 47 | println("DEBUG: NetworkBoundResource: Request returned NOTHING (HTTP 204)") 48 | onReturnError("HTTP 204. Returned NOTHING.") 49 | } 50 | } 51 | } 52 | 53 | fun onReturnError(message: String){ 54 | result.value = DataState.error(message) 55 | } 56 | 57 | abstract fun handleApiSuccessResponse(response: ApiSuccessResponse) 58 | 59 | abstract fun createCall(): LiveData> 60 | 61 | fun asLiveData() = result as LiveData> 62 | } 63 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/repository/Repository.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.repository 2 | 3 | import androidx.lifecycle.LiveData 4 | import com.codingwithmitch.mviexample.api.MyRetrofitBuilder 5 | import com.codingwithmitch.mviexample.model.BlogPost 6 | import com.codingwithmitch.mviexample.model.User 7 | import com.codingwithmitch.mviexample.ui.main.state.MainViewState 8 | import com.codingwithmitch.mviexample.util.* 9 | 10 | object Repository { 11 | 12 | fun getBlogPosts(): LiveData> { 13 | return object: NetworkBoundResource, MainViewState>(){ 14 | 15 | override fun handleApiSuccessResponse(response: ApiSuccessResponse>) { 16 | result.value = DataState.data( 17 | null, 18 | MainViewState( 19 | blogPosts = response.body, 20 | user = null 21 | ) 22 | ) 23 | } 24 | 25 | override fun createCall(): LiveData>> { 26 | return MyRetrofitBuilder.apiService.getBlogPosts() 27 | } 28 | 29 | }.asLiveData() 30 | } 31 | 32 | fun getUser(userId: String): LiveData> { 33 | return object: NetworkBoundResource(){ 34 | 35 | override fun handleApiSuccessResponse(response: ApiSuccessResponse) { 36 | result.value = DataState.data( 37 | null, 38 | MainViewState( 39 | blogPosts = null, 40 | user = response.body 41 | ) 42 | ) 43 | } 44 | 45 | override fun createCall(): LiveData> { 46 | return MyRetrofitBuilder.apiService.getUser(userId) 47 | } 48 | 49 | }.asLiveData() 50 | } 51 | } 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/ui/DataStateListener.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.ui 2 | 3 | import com.codingwithmitch.mviexample.util.DataState 4 | 5 | interface DataStateListener { 6 | 7 | fun onDataStateChange(dataState: DataState<*>?) 8 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/ui/main/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.ui.main 2 | 3 | import androidx.appcompat.app.AppCompatActivity 4 | import android.os.Bundle 5 | import android.view.View 6 | import android.widget.Toast 7 | import androidx.lifecycle.ViewModelProvider 8 | import com.codingwithmitch.mviexample.R 9 | import com.codingwithmitch.mviexample.ui.DataStateListener 10 | import com.codingwithmitch.mviexample.util.DataState 11 | import kotlinx.android.synthetic.main.activity_main.* 12 | 13 | class MainActivity : AppCompatActivity(), 14 | DataStateListener 15 | { 16 | override fun onDataStateChange(dataState: DataState<*>?) { 17 | handleDataStateChange(dataState) 18 | } 19 | 20 | lateinit var viewModel: MainViewModel 21 | 22 | override fun onCreate(savedInstanceState: Bundle?) { 23 | super.onCreate(savedInstanceState) 24 | setContentView(R.layout.activity_main) 25 | 26 | viewModel = ViewModelProvider(this).get(MainViewModel::class.java) 27 | 28 | showMainFragment() 29 | } 30 | 31 | fun showMainFragment(){ 32 | if(supportFragmentManager.fragments.size == 0){ 33 | supportFragmentManager.beginTransaction() 34 | .replace( 35 | R.id.fragment_container, 36 | MainFragment(), 37 | "MainFragment" 38 | ) 39 | .commit() 40 | } 41 | } 42 | 43 | fun handleDataStateChange(dataState: DataState<*>?){ 44 | dataState?.let{ 45 | // Handle loading 46 | showProgressBar(dataState.loading) 47 | 48 | // Handle Message 49 | dataState.message?.let{ event -> 50 | event.getContentIfNotHandled()?.let { message -> 51 | showToast(message) 52 | } 53 | } 54 | } 55 | } 56 | 57 | fun showToast(message: String){ 58 | Toast.makeText(this, message, Toast.LENGTH_SHORT).show() 59 | } 60 | 61 | fun showProgressBar(isVisible: Boolean){ 62 | if(isVisible){ 63 | progress_bar.visibility = View.VISIBLE 64 | } 65 | else{ 66 | progress_bar.visibility = View.INVISIBLE 67 | } 68 | } 69 | 70 | 71 | } 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/ui/main/MainFragment.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.ui.main 2 | 3 | import android.content.Context 4 | import android.os.Bundle 5 | import android.util.Log 6 | import android.view.* 7 | import androidx.core.widget.NestedScrollView 8 | import androidx.fragment.app.Fragment 9 | import androidx.lifecycle.Observer 10 | import androidx.lifecycle.ViewModelProvider 11 | import androidx.recyclerview.widget.LinearLayoutManager 12 | import androidx.recyclerview.widget.RecyclerView 13 | import com.bumptech.glide.Glide 14 | import com.codingwithmitch.mviexample.R 15 | import com.codingwithmitch.mviexample.model.BlogPost 16 | import com.codingwithmitch.mviexample.model.User 17 | import com.codingwithmitch.mviexample.ui.DataStateListener 18 | import com.codingwithmitch.mviexample.ui.main.state.MainStateEvent.* 19 | import com.codingwithmitch.mviexample.ui.main.state.MainViewState 20 | import com.codingwithmitch.mviexample.util.TopSpacingItemDecoration 21 | import kotlinx.android.synthetic.main.fragment_main.* 22 | 23 | class MainFragment : Fragment(), 24 | MainRecyclerAdapter.Interaction 25 | { 26 | 27 | private val TAG: String = "AppDebug" 28 | 29 | override fun onItemSelected(position: Int, item: BlogPost) { 30 | println("DEBUG: CLICKED ${position}") 31 | println("DEBUG: CLICKED ${item}") 32 | } 33 | 34 | lateinit var viewModel: MainViewModel 35 | 36 | lateinit var dataStateHandler: DataStateListener 37 | 38 | lateinit var mainRecyclerAdapter: MainRecyclerAdapter 39 | 40 | override fun onCreateView( 41 | inflater: LayoutInflater, container: ViewGroup?, 42 | savedInstanceState: Bundle? 43 | ): View? { 44 | // Inflate the layout for this fragment 45 | return inflater.inflate(R.layout.fragment_main, container, false) 46 | } 47 | 48 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 49 | super.onViewCreated(view, savedInstanceState) 50 | setHasOptionsMenu(true) 51 | 52 | viewModel = activity?.run { 53 | ViewModelProvider(this).get(MainViewModel::class.java) 54 | }?: throw Exception("Invalid Activity") 55 | 56 | 57 | initRecyclerView() 58 | subscribeObservers() 59 | } 60 | 61 | private fun initRecyclerView(){ 62 | recycler_view.apply { 63 | layoutManager = LinearLayoutManager(this@MainFragment.context) 64 | val topSpacingDecorator = TopSpacingItemDecoration(30) 65 | addItemDecoration(topSpacingDecorator) 66 | mainRecyclerAdapter = MainRecyclerAdapter(this@MainFragment) 67 | adapter = mainRecyclerAdapter 68 | } 69 | } 70 | 71 | private fun subscribeObservers(){ 72 | viewModel.dataState.observe(viewLifecycleOwner, Observer { dataState -> 73 | 74 | // Handle Loading and Message 75 | dataStateHandler.onDataStateChange(dataState) 76 | 77 | // handle Data 78 | dataState.data?.let{ event -> 79 | event.getContentIfNotHandled()?.let{ mainViewState -> 80 | 81 | println("DEBUG: DataState: ${mainViewState}") 82 | 83 | mainViewState.blogPosts?.let{ 84 | // set BlogPosts data 85 | 86 | viewModel.setBlogListData(it) 87 | } 88 | 89 | mainViewState.user?.let{ 90 | // set User data 91 | viewModel.setUser(it) 92 | } 93 | } 94 | } 95 | }) 96 | 97 | viewModel.viewState.observe(viewLifecycleOwner, Observer {viewState -> 98 | viewState.blogPosts?.let {blogPosts -> 99 | // set BlogPosts to RecyclerView 100 | println("DEBUG: Setting blog posts to RecyclerView: ${blogPosts}") 101 | mainRecyclerAdapter.submitList(blogPosts) 102 | } 103 | 104 | viewState.user?.let{ user -> 105 | // set User data to widgets 106 | println("DEBUG: Setting User data: ${user}") 107 | setUserProperties(user) 108 | 109 | } 110 | }) 111 | } 112 | 113 | fun setUserProperties(user: User){ 114 | email.setText(user.email) 115 | username.setText(user.username) 116 | 117 | view?.let{ 118 | Glide.with(it.context) 119 | .load(user.image) 120 | .into(image) 121 | } 122 | 123 | } 124 | 125 | fun triggerGetUserEvent(){ 126 | viewModel.setStateEvent(GetUserEvent("1")) 127 | } 128 | 129 | fun triggerGetBlogsEvent(){ 130 | viewModel.setStateEvent(GetBlogPostsEvent()) 131 | } 132 | 133 | override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { 134 | super.onCreateOptionsMenu(menu, inflater) 135 | inflater.inflate(R.menu.main_menu, menu) 136 | } 137 | 138 | override fun onOptionsItemSelected(item: MenuItem): Boolean { 139 | when(item.itemId){ 140 | R.id.action_get_blogs-> triggerGetBlogsEvent() 141 | 142 | R.id.action_get_user-> triggerGetUserEvent() 143 | } 144 | 145 | return super.onOptionsItemSelected(item) 146 | } 147 | 148 | override fun onAttach(context: Context) { 149 | super.onAttach(context) 150 | try{ 151 | dataStateHandler = context as DataStateListener 152 | }catch(e: ClassCastException){ 153 | println("$context must implement DataStateListener") 154 | } 155 | 156 | } 157 | } 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/ui/main/MainRecyclerAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.ui.main 2 | 3 | 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import androidx.recyclerview.widget.AsyncListDiffer 8 | import androidx.recyclerview.widget.DiffUtil 9 | import androidx.recyclerview.widget.RecyclerView 10 | import com.bumptech.glide.Glide 11 | import com.bumptech.glide.request.RequestOptions 12 | import com.codingwithmitch.mviexample.R 13 | import com.codingwithmitch.mviexample.model.BlogPost 14 | import kotlinx.android.synthetic.main.layout_blog_list_item.view.* 15 | 16 | class MainRecyclerAdapter(private val interaction: Interaction? = null) : 17 | RecyclerView.Adapter() { 18 | 19 | val DIFF_CALLBACK = object : DiffUtil.ItemCallback() { 20 | 21 | override fun areItemsTheSame(oldItem: BlogPost, newItem: BlogPost): Boolean { 22 | return oldItem.pk == newItem.pk 23 | } 24 | 25 | override fun areContentsTheSame(oldItem: BlogPost, newItem: BlogPost): Boolean { 26 | return oldItem == newItem 27 | } 28 | 29 | } 30 | private val differ = AsyncListDiffer(this, DIFF_CALLBACK) 31 | 32 | 33 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { 34 | 35 | return BlogPostViewHolder( 36 | LayoutInflater.from(parent.context).inflate( 37 | R.layout.layout_blog_list_item, 38 | parent, 39 | false 40 | ), 41 | interaction 42 | ) 43 | } 44 | 45 | override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { 46 | when (holder) { 47 | is BlogPostViewHolder -> { 48 | holder.bind(differ.currentList.get(position)) 49 | } 50 | } 51 | } 52 | 53 | override fun getItemCount(): Int { 54 | return differ.currentList.size 55 | } 56 | 57 | fun submitList(list: List) { 58 | differ.submitList(list) 59 | } 60 | 61 | class BlogPostViewHolder 62 | constructor( 63 | itemView: View, 64 | private val interaction: Interaction? 65 | ) : RecyclerView.ViewHolder(itemView) { 66 | 67 | fun bind(item: BlogPost) = with(itemView) { 68 | itemView.setOnClickListener { 69 | interaction?.onItemSelected(adapterPosition, item) 70 | } 71 | 72 | // need to shrink images b/c they are very high resolution 73 | val requestOptions = RequestOptions 74 | .overrideOf(1920, 1080) 75 | Glide.with(itemView.context) 76 | .applyDefaultRequestOptions(requestOptions) 77 | .load(item.image) 78 | .into(itemView.blog_image) 79 | 80 | itemView.blog_title.text = item.title 81 | } 82 | } 83 | 84 | interface Interaction { 85 | fun onItemSelected(position: Int, item: BlogPost) 86 | } 87 | } 88 | 89 | 90 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/ui/main/MainViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.ui.main 2 | 3 | import androidx.lifecycle.LiveData 4 | import androidx.lifecycle.MutableLiveData 5 | import androidx.lifecycle.Transformations 6 | import androidx.lifecycle.ViewModel 7 | import com.codingwithmitch.mviexample.model.BlogPost 8 | import com.codingwithmitch.mviexample.model.User 9 | import com.codingwithmitch.mviexample.repository.Repository 10 | import com.codingwithmitch.mviexample.ui.main.state.MainStateEvent 11 | import com.codingwithmitch.mviexample.ui.main.state.MainStateEvent.* 12 | import com.codingwithmitch.mviexample.ui.main.state.MainViewState 13 | import com.codingwithmitch.mviexample.util.AbsentLiveData 14 | import com.codingwithmitch.mviexample.util.DataState 15 | 16 | class MainViewModel : ViewModel(){ 17 | 18 | private val _stateEvent: MutableLiveData = MutableLiveData() 19 | private val _viewState: MutableLiveData = MutableLiveData() 20 | 21 | val viewState: LiveData 22 | get() = _viewState 23 | 24 | 25 | val dataState: LiveData> = Transformations 26 | .switchMap(_stateEvent){stateEvent -> 27 | stateEvent?.let { 28 | handleStateEvent(stateEvent) 29 | } 30 | } 31 | 32 | fun handleStateEvent(stateEvent: MainStateEvent): LiveData>{ 33 | println("DEBUG: New StateEvent detected: $stateEvent") 34 | when(stateEvent){ 35 | 36 | is GetBlogPostsEvent -> { 37 | return Repository.getBlogPosts() 38 | } 39 | 40 | is GetUserEvent -> { 41 | return Repository.getUser(stateEvent.userId) 42 | } 43 | 44 | is None ->{ 45 | return AbsentLiveData.create() 46 | } 47 | } 48 | } 49 | 50 | fun setBlogListData(blogPosts: List){ 51 | val update = getCurrentViewStateOrNew() 52 | update.blogPosts = blogPosts 53 | _viewState.value = update 54 | } 55 | 56 | fun setUser(user: User){ 57 | val update = getCurrentViewStateOrNew() 58 | update.user = user 59 | _viewState.value = update 60 | } 61 | 62 | fun getCurrentViewStateOrNew(): MainViewState { 63 | val value = viewState.value?.let{ 64 | it 65 | }?: MainViewState() 66 | return value 67 | } 68 | 69 | fun setStateEvent(event: MainStateEvent){ 70 | val state: MainStateEvent 71 | state = event 72 | _stateEvent.value = state 73 | } 74 | } 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/ui/main/state/MainStateEvent.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.ui.main.state 2 | 3 | sealed class MainStateEvent { 4 | 5 | class GetBlogPostsEvent: MainStateEvent() 6 | 7 | class GetUserEvent( 8 | val userId: String 9 | ): MainStateEvent() 10 | 11 | class None: MainStateEvent() 12 | 13 | 14 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/ui/main/state/MainViewState.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.ui.main.state 2 | 3 | import com.codingwithmitch.mviexample.model.BlogPost 4 | import com.codingwithmitch.mviexample.model.User 5 | 6 | data class MainViewState( 7 | 8 | var blogPosts: List? = null, 9 | 10 | var user: User? = null 11 | 12 | ) -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/util/AbsentLiveData.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.util 2 | 3 | import androidx.lifecycle.LiveData 4 | 5 | /** 6 | * A LiveData class that has `null` value. 7 | */ 8 | class AbsentLiveData private constructor(): LiveData() { 9 | 10 | init { 11 | // use post instead of set since this can be created on any thread 12 | postValue(null) 13 | } 14 | 15 | companion object { 16 | fun create(): LiveData { 17 | return AbsentLiveData() 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/util/Constants.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.util 2 | 3 | class Constants { 4 | 5 | companion object{ 6 | const val TESTING_NETWORK_DELAY = 1000L 7 | } 8 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/util/DataState.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.util 2 | 3 | 4 | data class DataState( 5 | var message: Event? = null, 6 | var loading: Boolean = false, 7 | var data: Event? = null 8 | ) 9 | { 10 | companion object { 11 | 12 | fun error( 13 | message: String 14 | ): DataState { 15 | return DataState( 16 | message = Event(message), 17 | loading = false, 18 | data = null 19 | ) 20 | } 21 | 22 | fun loading( 23 | isLoading: Boolean 24 | ): DataState { 25 | return DataState( 26 | message = null, 27 | loading = isLoading, 28 | data = null 29 | ) 30 | } 31 | 32 | fun data( 33 | message: String? = null, 34 | data: T? = null 35 | ): DataState { 36 | return DataState( 37 | message = Event.messageEvent(message), 38 | loading = false, 39 | data = Event.dataEvent(data) 40 | ) 41 | } 42 | } 43 | 44 | override fun toString(): String { 45 | return "DataState(message=$message,loading=$loading,data=$data)" 46 | } 47 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/util/Event.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.util 2 | 3 | /** 4 | * Used as a wrapper for data that is exposed via a LiveData that represents an event. 5 | */ 6 | class Event(private val content: T) { 7 | 8 | var hasBeenHandled = false 9 | private set // Allow external read but not write 10 | 11 | /** 12 | * Returns the content and prevents its use again. 13 | */ 14 | fun getContentIfNotHandled(): T? { 15 | return if (hasBeenHandled) { 16 | null 17 | } else { 18 | hasBeenHandled = true 19 | content 20 | } 21 | } 22 | 23 | /** 24 | * Returns the content, even if it's already been handled. 25 | */ 26 | fun peekContent(): T = content 27 | 28 | override fun toString(): String { 29 | return "Event(content=$content,hasBeenHandled=$hasBeenHandled)" 30 | } 31 | 32 | companion object{ 33 | 34 | // we don't want an event if there's no data 35 | fun dataEvent(data: T?): Event?{ 36 | data?.let { 37 | return Event(it) 38 | } 39 | return null 40 | } 41 | 42 | // we don't want an event if there is no message 43 | fun messageEvent(message: String?): Event?{ 44 | message?.let{ 45 | return Event(message) 46 | } 47 | return null 48 | } 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/util/GenericApiResponse.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.util 2 | 3 | 4 | import android.util.Log 5 | import retrofit2.Response 6 | 7 | /** 8 | * Copied from Architecture components google sample: 9 | * https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/api/ApiResponse.kt 10 | */ 11 | @Suppress("unused") // T is used in extending classes 12 | sealed class GenericApiResponse { 13 | 14 | companion object { 15 | private val TAG: String = "AppDebug" 16 | 17 | 18 | fun create(error: Throwable): ApiErrorResponse { 19 | return ApiErrorResponse(error.message ?: "unknown error") 20 | } 21 | 22 | fun create(response: Response): GenericApiResponse { 23 | 24 | Log.d(TAG, "GenericApiResponse: response: ${response}") 25 | Log.d(TAG, "GenericApiResponse: raw: ${response.raw()}") 26 | Log.d(TAG, "GenericApiResponse: headers: ${response.headers()}") 27 | Log.d(TAG, "GenericApiResponse: message: ${response.message()}") 28 | 29 | if(response.isSuccessful){ 30 | val body = response.body() 31 | if (body == null || response.code() == 204) { 32 | return ApiEmptyResponse() 33 | } 34 | else if(response.code() == 401){ 35 | return ApiErrorResponse("401 Unauthorized. Token may be invalid.") 36 | } 37 | else { 38 | return ApiSuccessResponse(body = body) 39 | } 40 | } 41 | else{ 42 | val msg = response.errorBody()?.string() 43 | val errorMsg = if (msg.isNullOrEmpty()) { 44 | response.message() 45 | } else { 46 | msg 47 | } 48 | return ApiErrorResponse(errorMsg ?: "unknown error") 49 | } 50 | } 51 | } 52 | } 53 | 54 | /** 55 | * separate class for HTTP 204 responses so that we can make ApiSuccessResponse's body non-null. 56 | */ 57 | class ApiEmptyResponse : GenericApiResponse() 58 | 59 | data class ApiSuccessResponse(val body: T) : GenericApiResponse() {} 60 | 61 | data class ApiErrorResponse(val errorMessage: String) : GenericApiResponse() 62 | -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/util/LiveDataCallAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.util 2 | 3 | 4 | import androidx.lifecycle.LiveData 5 | import retrofit2.Call 6 | import retrofit2.CallAdapter 7 | import retrofit2.Callback 8 | import retrofit2.Response 9 | import java.lang.reflect.Type 10 | import java.util.concurrent.atomic.AtomicBoolean 11 | 12 | class LiveDataCallAdapter(private val responseType: Type) : 13 | CallAdapter>> { 14 | 15 | override fun responseType() = responseType 16 | 17 | override fun adapt(call: Call): LiveData> { 18 | return object : LiveData>() { 19 | private var started = AtomicBoolean(false) 20 | override fun onActive() { 21 | super.onActive() 22 | if (started.compareAndSet(false, true)) { 23 | call.enqueue(object : Callback { 24 | override fun onResponse(call: Call, response: Response) { 25 | postValue(GenericApiResponse.create(response)) 26 | } 27 | 28 | override fun onFailure(call: Call, throwable: Throwable) { 29 | postValue(GenericApiResponse.create(throwable)) 30 | } 31 | }) 32 | } 33 | } 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/util/LiveDataCallAdapterFactory.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.util 2 | 3 | 4 | import androidx.lifecycle.LiveData 5 | import retrofit2.CallAdapter 6 | import retrofit2.CallAdapter.Factory 7 | import retrofit2.Retrofit 8 | import java.lang.reflect.ParameterizedType 9 | import java.lang.reflect.Type 10 | 11 | class LiveDataCallAdapterFactory : Factory() { 12 | override fun get( 13 | returnType: Type, 14 | annotations: Array, 15 | retrofit: Retrofit 16 | ): CallAdapter<*, *>? { 17 | if (Factory.getRawType(returnType) != LiveData::class.java) { 18 | return null 19 | } 20 | val observableType = Factory.getParameterUpperBound(0, returnType as ParameterizedType) 21 | val rawObservableType = Factory.getRawType(observableType) 22 | if (rawObservableType != GenericApiResponse::class.java) { 23 | throw IllegalArgumentException("type must be a resource") 24 | } 25 | if (observableType !is ParameterizedType) { 26 | throw IllegalArgumentException("resource must be parameterized") 27 | } 28 | val bodyType = Factory.getParameterUpperBound(0, observableType) 29 | return LiveDataCallAdapter(bodyType) 30 | } 31 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codingwithmitch/mviexample/util/TopSpacingItemDecoration.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample.util 2 | 3 | import androidx.recyclerview.widget.RecyclerView 4 | import android.graphics.Rect 5 | import android.view.View 6 | 7 | 8 | class TopSpacingItemDecoration(private val padding: Int) : RecyclerView.ItemDecoration() { 9 | 10 | override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { 11 | super.getItemOffsets(outRect, view, parent, state) 12 | outRect.top = padding 13 | } 14 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 18 | 19 | 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 13 | 14 | 20 | 21 | 28 | 29 | 34 | 35 | 42 | 43 | 51 | 52 | 53 | 54 | 61 | 62 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /app/src/main/res/layout/layout_blog_list_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 16 | 17 | 30 | 31 | 42 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /app/src/main/res/menu/main_menu.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 11 | 12 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | MVIExample 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/codingwithmitch/mviexample/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.codingwithmitch.mviexample 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 | } 18 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.3.50' 5 | repositories { 6 | google() 7 | jcenter() 8 | 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:3.5.0' 12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 13 | // NOTE: Do not place your application dependencies here; they belong 14 | // in the individual module build.gradle files 15 | } 16 | } 17 | 18 | allprojects { 19 | repositories { 20 | google() 21 | jcenter() 22 | 23 | } 24 | } 25 | 26 | task clean(type: Delete) { 27 | delete rootProject.buildDir 28 | } 29 | -------------------------------------------------------------------------------- /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=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mitchtabian/MVIExample/7d65d2775e7389e6ca3d36084cadbaf29dc56aee/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Fri Aug 30 15:23:29 PDT 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | rootProject.name='MVIExample' 3 | --------------------------------------------------------------------------------