├── .circleci └── config.yml ├── .gitignore ├── .idea ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── gradle.xml ├── misc.xml ├── runConfigurations.xml └── vcs.xml ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── carousell │ │ └── viewmodeladapter │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── carousell │ │ │ └── viewmodeladapter │ │ │ ├── MainActivity.kt │ │ │ ├── MainAdapter.kt │ │ │ ├── MainViewModel.kt │ │ │ ├── MyItem.kt │ │ │ └── items │ │ │ ├── EditHolder.kt │ │ │ ├── EditViewModel.kt │ │ │ ├── TextHolder.kt │ │ │ └── TextViewModel.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── adapter_edit.xml │ │ └── adapter_text.xml │ │ ├── menu │ │ └── main.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 │ └── carousell │ └── viewmodeladapter │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── viewmodeladapter ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src ├── androidTest └── java │ └── com │ └── carousell │ └── viewmodel │ └── adapter │ └── ExampleInstrumentedTest.kt ├── main ├── AndroidManifest.xml └── java │ └── com │ └── carousell │ └── viewmodel │ └── adapter │ ├── ItemViewModel.kt │ ├── ViewModelAdapter.kt │ └── ViewModelHolder.kt └── test └── java └── com └── carousell └── viewmodel └── adapter └── ExampleUnitTest.kt /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | orbs: 4 | android: circleci/android@0.2.0 5 | 6 | jobs: 7 | build: 8 | executor: android/android 9 | 10 | steps: 11 | - checkout 12 | - run: 13 | command: ./gradlew build 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | .idea/ 4 | /local.properties 5 | /.idea/caches 6 | /.idea/libraries 7 | /.idea/modules.xml 8 | /.idea/workspace.xml 9 | /.idea/navEditor.xml 10 | /.idea/assetWizardSettings.xml 11 | .DS_Store 12 | /build 13 | /captures 14 | .externalNativeBuild 15 | .cxx 16 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 20 | 22 | 23 | 24 | 26 | 27 | 28 |
29 | 30 | 31 | 32 | xmlns:android 33 | 34 | ^$ 35 | 36 | 37 | 38 |
39 |
40 | 41 | 42 | 43 | xmlns:.* 44 | 45 | ^$ 46 | 47 | 48 | BY_NAME 49 | 50 |
51 |
52 | 53 | 54 | 55 | .*:id 56 | 57 | http://schemas.android.com/apk/res/android 58 | 59 | 60 | 61 |
62 |
63 | 64 | 65 | 66 | .*:name 67 | 68 | http://schemas.android.com/apk/res/android 69 | 70 | 71 | 72 |
73 |
74 | 75 | 76 | 77 | name 78 | 79 | ^$ 80 | 81 | 82 | 83 |
84 |
85 | 86 | 87 | 88 | style 89 | 90 | ^$ 91 | 92 | 93 | 94 |
95 |
96 | 97 | 98 | 99 | .* 100 | 101 | ^$ 102 | 103 | 104 | BY_NAME 105 | 106 |
107 |
108 | 109 | 110 | 111 | .* 112 | 113 | http://schemas.android.com/apk/res/android 114 | 115 | 116 | ANDROID_ATTRIBUTE_ORDER 117 | 118 |
119 |
120 | 121 | 122 | 123 | .* 124 | 125 | .* 126 | 127 | 128 | BY_NAME 129 | 130 |
131 |
132 |
133 |
134 | 135 | 137 |
138 |
-------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Feedback 2 | 3 | We'd love the feedback from you. Please create [GitHub Issues](https://github.com/carousell/ViewModelAdapter/issues) for feature discussions, bug reports and anything you'd like us to know. Be sure to check out the [closed issues](https://github.com/carousell/ViewModelAdapter/issues?q=is:closed) before you open new ones. 4 | 5 | ## Contributing 6 | 7 | 1. Fork the repo. 8 | 9 | 2. Create a local feature branch from the latest `master`, prefix it with **feature/** and use **hyphen-separated-words** to name your branch: 10 | 11 | ```sh 12 | git checkout -b feature/your-branch 13 | ``` 14 | 15 | 3. Add your changes and push it to your fork 16 | 17 | 4. Create a pull request -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2020 Carousell 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ViewModelAdapter 2 | 3 | [![CircleCI](https://circleci.com/gh/carousell/ViewModelAdapter.svg?style=shield)](https://circleci.com/gh/carousell/ViewModelAdapter) 4 | [![jitpack](https://jitpack.io/v/carousell/ViewModelAdapter.svg)](https://jitpack.io/#carousell/ViewModelAdapter) 5 | 6 | ViewModelAdapter is a project that apply MVVM pattern for RecyclerView.Adapter in Android. 7 | 8 | ## Install 9 | 10 | With setup of Jitpack first, than add dependency in your build.gradle 11 | ```groovy 12 | implementation 'com.github.carousell:ViewModelAdapter:0.2' 13 | ``` 14 | 15 | ## Concept 16 | 17 | We want to make `Activity`/`Fragment` to be pure container and delegate the functionality to elements inside `RecyclerView` to fulfill clean and scaleable architecture. 18 | We use ViewModel as the data source of RecyclerView, and generate corresponding ViewHolder/View that will bind with the ViewModel and observe change or execute actions. 19 | 20 | ## Usage & Example 21 | 22 | - Create a list of `ViewModels` that extends `ItemViewModel` that represent the different items that will be displayed into the `RecyclerView`. The following methods should be implemented: 23 | - getKey: Provide a unique key to the ViewModel. 24 | - compare: Compare different `ViewModel` and return if they are identical. 25 | 26 | Example: 27 | ```kotlin 28 | class TextViewModel(private val item: TextItem) : ItemViewModel() { 29 | 30 | override fun getKey(): String { 31 | return item.key 32 | } 33 | 34 | override fun compare(viewModel: ItemViewModel): Boolean { 35 | if (viewModel is TextViewModel) { 36 | return viewModel.text == text 37 | } 38 | return false 39 | } 40 | } 41 | ``` 42 | - Create a list of `ViewHolders` that extends `ViewModelHolder` to interact with your corresponding `ViewModel`. The following methods should be implemented: 43 | - onBind: Subscribe to the data sources (LiveData, RxJava, etc) provided by your ViewModel. 44 | - onUnbind: Unsubscribe to the data sources (LiveData, RxJava, etc) provided by your ViewModel. 45 | 46 | Example: 47 | ```kotlin 48 | class TextHolder(itemView: View, private val lifecycleOwner: LifecycleOwner) : 49 | ViewModelHolder(itemView), Observer { 50 | 51 | override fun onBind(viewModel: TextViewModel) { 52 | viewModel.liveData().observe(lifecycleOwner, this) 53 | } 54 | 55 | override fun onUnbind(viewModel: TextViewModel) { 56 | viewModel.liveData().removeObserver(this) 57 | } 58 | 59 | override fun onChanged(string: String?) { 60 | itemView.text.text = string 61 | } 62 | } 63 | ``` 64 | - Create adapter extends `ViewModelAdapter` which will handle the `ViewModel` binding for you. 65 | The only method need to implement: 66 | - onCreateViewHolder: Create the corresponding `ItemViewModel` via different modelType. 67 | 68 | Example: 69 | ```kotlin 70 | override fun onCreateViewHolder( 71 | parent: ViewGroup, 72 | modelType: Class 73 | ): ViewModelHolder { 74 | val layoutInflater = LayoutInflater.from(parent.context) 75 | return when (modelType) { 76 | TextViewModel::class.java -> TextHolder( 77 | layoutInflater.inflate(R.layout.adapter_text, parent, false), 78 | lifecycleOwner 79 | ) 80 | EditViewModel::class.java -> EditHolder( 81 | layoutInflater.inflate(R.layout.adapter_edit, parent, false) 82 | ) 83 | else -> throw RuntimeException("Not support") 84 | } 85 | } 86 | ``` 87 | Go to `./app` module for more information. 88 | 89 | ## Contributing 90 | 91 | Thank you for being interested in contributing to this project. Check out the [CONTRIBUTING](https://github.com/carousell/ViewModelAdapter/blob/master/CONTRIBUTING.md) document for more info. 92 | 93 | ## About 94 | 95 | Carousell 96 | 97 | **ViewModelAdapter** is created and maintained by [Carousell](https://carousell.com/). Help us improve this project! We'd love the [feedback](https://github.com/carousell/ViewModelAdapter/issues) from you. 98 | 99 | We're hiring! Find out more at 100 | 101 | ## License 102 | 103 | **ViewModelAdapter** is released under Apache License 2.0. 104 | See [LICENSE](https://github.com/carousell/ViewModelAdapter/blob/master/LICENSE) for more details. 105 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | 5 | android { 6 | compileSdkVersion 30 7 | buildToolsVersion "30.0.2" 8 | 9 | defaultConfig { 10 | applicationId "com.carousell.viewmodeladapter" 11 | minSdkVersion 16 12 | targetSdkVersion 30 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | 26 | } 27 | 28 | dependencies { 29 | implementation project(":viewmodeladapter") 30 | // implementation 'com.github.carousell:viewmodeladapter:0.1' 31 | implementation fileTree(dir: 'libs', include: ['*.jar']) 32 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 33 | implementation 'androidx.appcompat:appcompat:1.2.0' 34 | implementation 'androidx.core:core-ktx:1.3.2' 35 | implementation 'androidx.constraintlayout:constraintlayout:2.0.2' 36 | testImplementation 'junit:junit:4.13' 37 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 38 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 39 | implementation 'androidx.recyclerview:recyclerview:1.1.0' 40 | implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' 41 | implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' 42 | } 43 | -------------------------------------------------------------------------------- /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/carousell/viewmodeladapter/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter 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.carousell.viewmodeladapter", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/carousell/viewmodeladapter/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter 2 | 3 | import android.os.Bundle 4 | import android.view.Menu 5 | import android.view.MenuItem 6 | import androidx.appcompat.app.AppCompatActivity 7 | import androidx.lifecycle.Observer 8 | import androidx.lifecycle.ViewModelProvider 9 | import androidx.recyclerview.widget.LinearLayoutManager 10 | import kotlinx.android.synthetic.main.activity_main.* 11 | 12 | class MainActivity : AppCompatActivity() { 13 | 14 | private lateinit var viewModel: MainViewModel 15 | 16 | override fun onCreate(savedInstanceState: Bundle?) { 17 | super.onCreate(savedInstanceState) 18 | setContentView(R.layout.activity_main) 19 | 20 | val adapter = MainAdapter(this) 21 | recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) 22 | recyclerView.adapter = adapter 23 | swipeRefreshLayout.setOnRefreshListener { 24 | viewModel.refresh() 25 | } 26 | viewModel = ViewModelProvider(this).get(MainViewModel::class.java) 27 | viewModel.getLiveData().observe(this, Observer { 28 | swipeRefreshLayout.isRefreshing = false 29 | adapter.submitList(it) 30 | }) 31 | 32 | } 33 | 34 | override fun onCreateOptionsMenu(menu: Menu?): Boolean { 35 | menuInflater.inflate(R.menu.main, menu) 36 | return super.onCreateOptionsMenu(menu) 37 | } 38 | 39 | override fun onOptionsItemSelected(item: MenuItem): Boolean { 40 | if (item.itemId == R.id.add) { 41 | viewModel.addNewItem() 42 | return true 43 | } 44 | return super.onOptionsItemSelected(item) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/com/carousell/viewmodeladapter/MainAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter 2 | 3 | import android.view.LayoutInflater 4 | import android.view.ViewGroup 5 | import androidx.lifecycle.LifecycleOwner 6 | import com.carousell.viewmodel.adapter.ItemViewModel 7 | import com.carousell.viewmodel.adapter.ViewModelAdapter 8 | import com.carousell.viewmodel.adapter.ViewModelHolder 9 | import com.carousell.viewmodeladapter.items.EditHolder 10 | import com.carousell.viewmodeladapter.items.EditViewModel 11 | import com.carousell.viewmodeladapter.items.TextHolder 12 | import com.carousell.viewmodeladapter.items.TextViewModel 13 | 14 | class MainAdapter( 15 | private val lifecycleOwner: LifecycleOwner 16 | ) : ViewModelAdapter() { 17 | 18 | override fun onCreateViewHolder( 19 | parent: ViewGroup, 20 | modelType: Class 21 | ): ViewModelHolder { 22 | val layoutInflater = LayoutInflater.from(parent.context) 23 | return when (modelType) { 24 | TextViewModel::class.java -> TextHolder( 25 | layoutInflater.inflate(R.layout.adapter_text, parent, false), 26 | lifecycleOwner 27 | ) 28 | EditViewModel::class.java -> EditHolder( 29 | layoutInflater.inflate(R.layout.adapter_edit, parent, false) 30 | ) 31 | else -> throw RuntimeException("Not support") 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /app/src/main/java/com/carousell/viewmodeladapter/MainViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter 2 | 3 | import androidx.lifecycle.* 4 | import com.carousell.viewmodel.adapter.ItemViewModel 5 | import com.carousell.viewmodeladapter.items.EditViewModel 6 | import com.carousell.viewmodeladapter.items.TextViewModel 7 | 8 | class MainViewModel : ViewModel() { 9 | 10 | private val liveData = MutableLiveData>() 11 | private val itemViewModelStore = ViewModelStore() 12 | 13 | init { 14 | generateViewModels(getData()) 15 | } 16 | 17 | fun getLiveData(): LiveData> { 18 | return liveData 19 | } 20 | 21 | fun refresh() { 22 | itemViewModelStore.clear() 23 | generateViewModels(getData()) 24 | } 25 | 26 | // Generate data 27 | private fun getData(): MutableList { 28 | return IntRange(0, 10000).map { index -> 29 | if (index % 2 == 0) { 30 | TextItem(index.toString(), "Item $index") 31 | } else { 32 | EditItem(index.toString(), "Item $index") 33 | } 34 | }.toMutableList() 35 | } 36 | 37 | private fun generateViewModels(list: List) { 38 | liveData.value = list.map { 39 | generateViewModel(it) 40 | } 41 | } 42 | 43 | private fun generateViewModel(item: MyItem): ItemViewModel { 44 | return ViewModelProvider( 45 | itemViewModelStore, 46 | getFactory(item) 47 | ).get(item.key, getViewModelClass(item)) 48 | } 49 | 50 | private fun getViewModelClass(item: MyItem): Class = when (item) { 51 | is TextItem -> TextViewModel::class.java 52 | is EditItem -> EditViewModel::class.java 53 | } 54 | 55 | private fun getFactory(item: MyItem): ViewModelProvider.Factory = when (item) { 56 | is TextItem -> TextViewModel.Factory(item) 57 | is EditItem -> EditViewModel.Factory(item) 58 | } 59 | 60 | fun addNewItem() { 61 | val item = EditItem( 62 | System.currentTimeMillis().toString(), 63 | "add new" + System.currentTimeMillis() 64 | ) 65 | val list = liveData.value?.toMutableList() 66 | list?.add(2, generateViewModel(item)) 67 | liveData.value = list 68 | } 69 | } -------------------------------------------------------------------------------- /app/src/main/java/com/carousell/viewmodeladapter/MyItem.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter 2 | 3 | sealed class MyItem( 4 | open val key: String 5 | ) 6 | 7 | data class TextItem( 8 | override val key: String, 9 | val data: String 10 | ) : MyItem(key) 11 | 12 | data class EditItem( 13 | override val key: String, 14 | val data: String 15 | ) : MyItem(key) -------------------------------------------------------------------------------- /app/src/main/java/com/carousell/viewmodeladapter/items/EditHolder.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter.items 2 | 3 | import android.text.Editable 4 | import android.text.TextWatcher 5 | import android.view.View 6 | import com.carousell.viewmodel.adapter.ViewModelHolder 7 | import kotlinx.android.synthetic.main.adapter_edit.view.* 8 | 9 | class EditHolder(itemView: View) : 10 | ViewModelHolder(itemView), TextWatcher { 11 | 12 | override fun onBind(viewModel: EditViewModel) { 13 | itemView.edit.addTextChangedListener(this) 14 | itemView.edit.setText(viewModel.getValue()) 15 | } 16 | 17 | override fun onUnbind(viewModel: EditViewModel) { 18 | } 19 | 20 | override fun afterTextChanged(p0: Editable?) { 21 | viewModel?.setValue(p0.toString()) 22 | } 23 | 24 | override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { 25 | } 26 | 27 | override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { 28 | } 29 | } -------------------------------------------------------------------------------- /app/src/main/java/com/carousell/viewmodeladapter/items/EditViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter.items 2 | 3 | import androidx.lifecycle.ViewModel 4 | import androidx.lifecycle.ViewModelProvider 5 | import com.carousell.viewmodel.adapter.ItemViewModel 6 | import com.carousell.viewmodeladapter.EditItem 7 | 8 | class EditViewModel(private val item: EditItem) : ItemViewModel() { 9 | private var text = item.data 10 | 11 | override fun getKey(): String { 12 | return item.key 13 | } 14 | 15 | override fun compare(viewModel: ItemViewModel): Boolean { 16 | if (viewModel is EditViewModel) { 17 | return viewModel.text == text 18 | } 19 | return false 20 | } 21 | 22 | fun getValue(): String { 23 | return text 24 | } 25 | 26 | fun setValue(text: String) { 27 | this.text = text 28 | } 29 | 30 | class Factory(private val item: EditItem) : 31 | ViewModelProvider.Factory { 32 | 33 | @Suppress("UNCHECKED_CAST") 34 | override fun create(modelClass: Class): T { 35 | return EditViewModel(item) as T 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /app/src/main/java/com/carousell/viewmodeladapter/items/TextHolder.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter.items 2 | 3 | import android.view.View 4 | import androidx.lifecycle.LifecycleOwner 5 | import androidx.lifecycle.Observer 6 | import com.carousell.viewmodel.adapter.ViewModelHolder 7 | import kotlinx.android.synthetic.main.adapter_text.view.* 8 | 9 | class TextHolder(itemView: View, private val lifecycleOwner: LifecycleOwner) : 10 | ViewModelHolder(itemView), Observer { 11 | 12 | override fun onBind(viewModel: TextViewModel) { 13 | viewModel.liveData().observe(lifecycleOwner, this) 14 | } 15 | 16 | override fun onUnbind(viewModel: TextViewModel) { 17 | viewModel.liveData().removeObserver(this) 18 | } 19 | 20 | override fun onChanged(string: String?) { 21 | itemView.text.text = string 22 | } 23 | } -------------------------------------------------------------------------------- /app/src/main/java/com/carousell/viewmodeladapter/items/TextViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter.items 2 | 3 | import androidx.lifecycle.LiveData 4 | import androidx.lifecycle.MutableLiveData 5 | import androidx.lifecycle.ViewModel 6 | import androidx.lifecycle.ViewModelProvider 7 | import com.carousell.viewmodel.adapter.ItemViewModel 8 | import com.carousell.viewmodeladapter.TextItem 9 | 10 | class TextViewModel(private val item: TextItem) : ItemViewModel() { 11 | private val liveData = MutableLiveData() 12 | private val text = item.data 13 | 14 | init { 15 | this.liveData.value = text 16 | } 17 | 18 | override fun getKey(): String { 19 | return item.key 20 | } 21 | 22 | override fun compare(viewModel: ItemViewModel): Boolean { 23 | if (viewModel is TextViewModel) { 24 | return viewModel.text == text 25 | } 26 | return false 27 | } 28 | 29 | fun liveData(): LiveData { 30 | return liveData 31 | } 32 | 33 | class Factory(private val item: TextItem) : 34 | ViewModelProvider.Factory { 35 | 36 | @Suppress("UNCHECKED_CAST") 37 | override fun create(modelClass: Class): T { 38 | return TextViewModel(item) as T 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /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 | 8 | 9 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/layout/adapter_edit.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /app/src/main/res/layout/adapter_text.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /app/src/main/res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 8 | -------------------------------------------------------------------------------- /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/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #6200EE 4 | #3700B3 5 | #03DAC5 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ViewModelAdapter 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/carousell/viewmodeladapter/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodeladapter 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.4.10' 5 | repositories { 6 | google() 7 | jcenter() 8 | mavenLocal() 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:4.1.0' 12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 13 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' 14 | // NOTE: Do not place your application dependencies here; they belong 15 | // in the individual module build.gradle files 16 | } 17 | } 18 | 19 | allprojects { 20 | repositories { 21 | google() 22 | jcenter() 23 | mavenLocal() 24 | } 25 | } 26 | 27 | task clean(type: Delete) { 28 | delete rootProject.buildDir 29 | } 30 | -------------------------------------------------------------------------------- /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/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Oct 15 17:34:27 CST 2020 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-6.5-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 | rootProject.name = 'ViewModelAdapter' 2 | include ':app', ':viewmodeladapter' 3 | -------------------------------------------------------------------------------- /viewmodeladapter/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /viewmodeladapter/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | apply plugin: 'com.github.dcendents.android-maven' 5 | 6 | group = 'com.github.carousell' 7 | 8 | android { 9 | compileSdkVersion 30 10 | buildToolsVersion "30.0.2" 11 | 12 | defaultConfig { 13 | minSdkVersion 16 14 | targetSdkVersion 30 15 | versionCode 1 16 | versionName "1.0" 17 | 18 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 19 | consumerProguardFiles 'consumer-rules.pro' 20 | } 21 | 22 | buildTypes { 23 | release { 24 | minifyEnabled false 25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 26 | } 27 | } 28 | 29 | } 30 | 31 | dependencies { 32 | implementation fileTree(dir: 'libs', include: ['*.jar']) 33 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 34 | implementation 'androidx.appcompat:appcompat:1.2.0' 35 | implementation 'androidx.core:core-ktx:1.3.2' 36 | testImplementation 'junit:junit:4.13' 37 | androidTestImplementation 'androidx.test.ext:junit:1.1.2' 38 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' 39 | implementation 'androidx.recyclerview:recyclerview:1.1.0' 40 | } 41 | -------------------------------------------------------------------------------- /viewmodeladapter/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/carousell/ViewModelAdapter/4ff213b520d8e50000083a5323e07f4e21d0b03a/viewmodeladapter/consumer-rules.pro -------------------------------------------------------------------------------- /viewmodeladapter/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 | -------------------------------------------------------------------------------- /viewmodeladapter/src/androidTest/java/com/carousell/viewmodel/adapter/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodel.adapter 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.carousell.viewmodel.adapter.test", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /viewmodeladapter/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /viewmodeladapter/src/main/java/com/carousell/viewmodel/adapter/ItemViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodel.adapter 2 | 3 | import androidx.lifecycle.ViewModel 4 | import androidx.recyclerview.widget.DiffUtil 5 | 6 | /** 7 | * ViewModel which will be used to interact with ViewModelHolder 8 | */ 9 | abstract class ItemViewModel : ViewModel() { 10 | /** 11 | * Unique key to identify ViewModel. Will be used in ItemDiffCallback 12 | */ 13 | abstract fun getKey(): String 14 | 15 | /** 16 | * Check whether two ViewModels have the same content. Will be used in ItemDiffCallback 17 | */ 18 | abstract fun compare(viewModel: ItemViewModel): Boolean 19 | 20 | /** 21 | * Default implementation of DiffUtil.ItemCallback for ItemViewModel, can be overridden to implement custom logic 22 | */ 23 | class ItemDiffCallback : DiffUtil.ItemCallback() { 24 | override fun areItemsTheSame(oldItem: ItemViewModel, newItem: ItemViewModel): Boolean { 25 | return oldItem.getKey() == newItem.getKey() 26 | } 27 | 28 | override fun areContentsTheSame(oldItem: ItemViewModel, newItem: ItemViewModel): Boolean { 29 | return oldItem.compare(newItem) 30 | } 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /viewmodeladapter/src/main/java/com/carousell/viewmodel/adapter/ViewModelAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodel.adapter 2 | 3 | import android.view.ViewGroup 4 | import androidx.recyclerview.widget.DiffUtil 5 | import androidx.recyclerview.widget.ListAdapter 6 | 7 | /** 8 | * ViewModelAdapter to handle ViewModel List as data source 9 | */ 10 | abstract class ViewModelAdapter(callback: DiffUtil.ItemCallback = ItemViewModel.ItemDiffCallback()) : 11 | ListAdapter>(callback) { 12 | 13 | /** 14 | * Mapping model class into int ViewType 15 | */ 16 | private val modelTypeMapping = mutableMapOf, Int>() 17 | 18 | /** 19 | * Mapping int ViewType into model class 20 | */ 21 | private val typeModelMapping = mutableMapOf>() 22 | 23 | override fun onBindViewHolder(holder: ViewModelHolder, position: Int) { 24 | holder.bind(getItem(position)) 25 | } 26 | 27 | override fun onViewRecycled(holder: ViewModelHolder) { 28 | holder.unbind() 29 | } 30 | 31 | final override fun getItemViewType(position: Int): Int { 32 | val clz = getItem(position).javaClass 33 | 34 | return modelTypeMapping[clz] ?: run { 35 | val index = modelTypeMapping.size 36 | modelTypeMapping[clz] = index 37 | typeModelMapping[index] = clz 38 | return@run index 39 | } 40 | } 41 | 42 | final override fun onCreateViewHolder( 43 | parent: ViewGroup, 44 | viewType: Int 45 | ): ViewModelHolder { 46 | return typeModelMapping[viewType]?.let { 47 | onCreateViewHolder(parent, it) 48 | } ?: throw RuntimeException("No support onCreateViewHolder") 49 | } 50 | 51 | /** 52 | * Create ViewHolder by corresponding ItemViewModel class 53 | */ 54 | abstract fun onCreateViewHolder( 55 | parent: ViewGroup, 56 | modelType: Class 57 | ): ViewModelHolder 58 | } -------------------------------------------------------------------------------- /viewmodeladapter/src/main/java/com/carousell/viewmodel/adapter/ViewModelHolder.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodel.adapter 2 | 3 | import android.view.View 4 | import androidx.recyclerview.widget.RecyclerView 5 | 6 | /** 7 | * Base ViewHolder for ViewModelAdapter, will bind and unbind the related ItemViewModel when the screen is scrolled 8 | */ 9 | abstract class ViewModelHolder(itemView: View) : 10 | RecyclerView.ViewHolder(itemView) { 11 | 12 | /** 13 | * The ViewModel currently bound to this ViewModelHolder 14 | */ 15 | var viewModel: T? = null 16 | 17 | /** 18 | * The entry point for ViewModelAdapter to bind ItemViewModel 19 | */ 20 | @Suppress("UNCHECKED_CAST") 21 | fun bind(viewModel: ItemViewModel) { 22 | (viewModel as? T)?.let { bindInternal(it) } 23 | } 24 | 25 | /** 26 | * The implementation of bind(viewModel), will call unbind(), keep viewModel reference and onBind() 27 | */ 28 | private fun bindInternal(viewModel: T) { 29 | unbind() 30 | this.viewModel = viewModel 31 | onBind(viewModel) 32 | } 33 | 34 | /** 35 | * Unbind event, will be called when new ViewModel is about to bind or the ViewHolder is been recycled. 36 | */ 37 | fun unbind() { 38 | this.viewModel?.let { 39 | onUnbind(it) 40 | } 41 | } 42 | 43 | /** 44 | * Callback of bind event 45 | * @param viewModel ViewModel currently bound to this ViewModelHolder 46 | */ 47 | abstract fun onBind(viewModel: T) 48 | 49 | /** 50 | * Callback of unbind event 51 | * @param viewModel ViewModel which will no longer be bound to this ViewModelHolder 52 | */ 53 | abstract fun onUnbind(viewModel: T) 54 | } -------------------------------------------------------------------------------- /viewmodeladapter/src/test/java/com/carousell/viewmodel/adapter/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.carousell.viewmodel.adapter 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 | --------------------------------------------------------------------------------