├── settings.gradle ├── observablerm ├── src │ ├── main │ │ ├── res │ │ │ └── values │ │ │ │ └── strings.xml │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── me │ │ │ └── silong │ │ │ └── snappyadapter │ │ │ ├── RxRecyclerViewCallback.java │ │ │ ├── SnappyDiffCallback.java │ │ │ ├── RxSortedList.java │ │ │ ├── RxSortedListCallback.java │ │ │ └── SnappySortedList.java │ ├── test │ │ └── java │ │ │ └── me │ │ │ └── silong │ │ │ └── observablerm │ │ │ ├── ExampleUnitTest.java │ │ │ └── ObservableAdapterManagerTest.java │ └── androidTest │ │ └── java │ │ └── me │ │ └── silong │ │ └── observablerm │ │ └── ApplicationTest.java ├── proguard-rules.pro └── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── app ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── drawable-hdpi │ │ │ │ └── ic_more_vert_white_36dp.png │ │ │ ├── drawable-mdpi │ │ │ │ └── ic_more_vert_white_36dp.png │ │ │ ├── drawable-xhdpi │ │ │ │ └── ic_more_vert_white_36dp.png │ │ │ ├── drawable-xxhdpi │ │ │ │ └── ic_more_vert_white_36dp.png │ │ │ ├── drawable-xxxhdpi │ │ │ │ └── ic_more_vert_white_36dp.png │ │ │ ├── layout │ │ │ │ ├── activity_main.xml │ │ │ │ └── item.xml │ │ │ └── menu │ │ │ │ └── menu_action.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── silong │ │ │ │ └── snappyrecycleradapter │ │ │ │ ├── adapter │ │ │ │ ├── SyncList.java │ │ │ │ ├── RxUserRecyclerViewAdapter.java │ │ │ │ ├── SortedListRecyclerViewAdapter.java │ │ │ │ └── RegularRecyclerViewAdapter.java │ │ │ │ ├── model │ │ │ │ ├── User.java │ │ │ │ └── DataFactory.java │ │ │ │ ├── ItemViewHolder.java │ │ │ │ ├── App.java │ │ │ │ ├── MainActivity.java │ │ │ │ └── RecyclerViewActivity.java │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── silong │ │ │ └── snappyrecycleradapter │ │ │ └── ExampleUnitTest.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── silong │ │ └── snappyrecycleradapter │ │ └── ApplicationTest.java ├── proguard-rules.pro └── build.gradle ├── gradle.properties ├── config.gradle ├── gradlew.bat ├── README.md └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':observablerm', ':app' 2 | -------------------------------------------------------------------------------- /observablerm/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | My Library 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | ObservableRecyclerViewAdapterManager 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_more_vert_white_36dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/drawable-hdpi/ic_more_vert_white_36dp.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_more_vert_white_36dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/drawable-mdpi/ic_more_vert_white_36dp.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_more_vert_white_36dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/drawable-xhdpi/ic_more_vert_white_36dp.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_more_vert_white_36dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/drawable-xxhdpi/ic_more_vert_white_36dp.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxxhdpi/ic_more_vert_white_36dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/longbkiter07/SnappyRecyclerAdapter/HEAD/app/src/main/res/drawable-xxxhdpi/ic_more_vert_white_36dp.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 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-2.10-all.zip 7 | -------------------------------------------------------------------------------- /observablerm/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /observablerm/src/test/java/me/silong/observablerm/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package me.silong.observablerm; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | 12 | @Test 13 | public void addition_isCorrect() throws Exception { 14 | assertEquals(4, 2 + 2); 15 | } 16 | } -------------------------------------------------------------------------------- /app/src/test/java/com/silong/snappyrecycleradapter/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * To work on unit tests, switch the Test Artifact in the Build Variants view. 9 | */ 10 | public class ExampleUnitTest { 11 | @Test 12 | public void addition_isCorrect() throws Exception { 13 | assertEquals(4, 2 + 2); 14 | } 15 | } -------------------------------------------------------------------------------- /observablerm/src/androidTest/java/me/silong/observablerm/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package me.silong.observablerm; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | 11 | public ApplicationTest() { 12 | super(Application.class); 13 | } 14 | } -------------------------------------------------------------------------------- /app/src/androidTest/java/com/silong/snappyrecycleradapter/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/adapter/SyncList.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter.adapter; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Created by SILONG on 4/19/17. 7 | */ 8 | 9 | public interface SyncList { 10 | 11 | void add(T t); 12 | 13 | void add(List users); 14 | 15 | void set(T t, int pos); 16 | 17 | void remove(T user); 18 | 19 | void remove(int index); 20 | 21 | void set(List users); 22 | 23 | void clear(); 24 | 25 | int getItemCount(); 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/silong/Documents/Development/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /observablerm/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/silong/Documents/Development/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/model/User.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter.model; 2 | 3 | import android.text.TextUtils; 4 | 5 | /** 6 | * Created by SILONG on 8/28/16. 7 | */ 8 | public class User { 9 | 10 | public final String id; 11 | 12 | public final int age; 13 | 14 | public final Gender gender; 15 | 16 | public final String name; 17 | 18 | public User(String id, String name, int age, Gender gender) { 19 | this.id = id; 20 | this.age = age; 21 | this.gender = gender; 22 | this.name = name; 23 | } 24 | 25 | @Override 26 | public boolean equals(Object obj) { 27 | if (obj instanceof User) { 28 | return TextUtils.equals(((User) obj).id, id); 29 | } else { 30 | return super.equals(obj); 31 | } 32 | } 33 | 34 | public enum Gender { 35 | male, 36 | female 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/ItemViewHolder.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter; 2 | 3 | import com.silong.snappyrecycleradapter.model.User; 4 | 5 | import android.support.v7.widget.RecyclerView; 6 | import android.view.View; 7 | import android.widget.TextView; 8 | 9 | import java.util.Locale; 10 | 11 | 12 | /** 13 | * Created by SILONG on 8/28/16. 14 | */ 15 | public class ItemViewHolder extends RecyclerView.ViewHolder { 16 | 17 | private TextView vName, vAge, vGender; 18 | 19 | public ItemViewHolder(View itemView) { 20 | super(itemView); 21 | vName = (TextView) itemView.findViewById(R.id.item_name); 22 | vAge = (TextView) itemView.findViewById(R.id.item_age); 23 | vGender = (TextView) itemView.findViewById(R.id.item_gender); 24 | } 25 | 26 | public void bind(User user) { 27 | vName.setText(user.name); 28 | vAge.setText(String.format(Locale.US, "%d years old", user.age)); 29 | vGender.setText(user.gender.name()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /observablerm/src/main/java/me/silong/snappyadapter/RxRecyclerViewCallback.java: -------------------------------------------------------------------------------- 1 | package me.silong.snappyadapter; 2 | 3 | import android.support.v7.widget.RecyclerView; 4 | 5 | /** 6 | * Created by SILONG on 4/24/17. 7 | */ 8 | 9 | public abstract class RxRecyclerViewCallback extends RxSortedListCallback { 10 | 11 | private final RecyclerView.Adapter mAdapter; 12 | 13 | public RxRecyclerViewCallback(RecyclerView.Adapter adapter) { 14 | mAdapter = adapter; 15 | } 16 | 17 | @Override 18 | public void onChanged(int position, int count) { 19 | mAdapter.notifyItemChanged(position, count); 20 | } 21 | 22 | @Override 23 | public void onInserted(int position, int count) { 24 | mAdapter.notifyItemRangeInserted(position, count); 25 | } 26 | 27 | @Override 28 | public void onRemoved(int position, int count) { 29 | mAdapter.notifyItemRangeRemoved(position, count); 30 | } 31 | 32 | @Override 33 | public void onMoved(int fromPosition, int toPosition) { 34 | mAdapter.notifyItemMoved(fromPosition, toPosition); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /app/src/main/res/layout/item.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 17 | 25 | 33 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: "me.tatarka.retrolambda" 3 | 4 | android { 5 | compileSdkVersion 24 6 | buildToolsVersion "24.0.1" 7 | compileOptions { 8 | sourceCompatibility JavaVersion.VERSION_1_8 9 | targetCompatibility JavaVersion.VERSION_1_8 10 | } 11 | defaultConfig { 12 | applicationId "com.silong.snappyrecycleradapter" 13 | minSdkVersion 16 14 | targetSdkVersion 24 15 | versionCode 1 16 | versionName "1.0" 17 | } 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | } 25 | 26 | dependencies { 27 | compile fileTree(dir: 'libs', include: ['*.jar']) 28 | testCompile 'junit:junit:4.12' 29 | compile 'com.android.support:appcompat-v7:24.2.0' 30 | compile 'com.android.support:recyclerview-v7:24.2.0' 31 | debugCompile "com.github.brianPlummer:tinydancer:0.1.1" 32 | releaseCompile "com.github.brianPlummer:tinydancer-noop:0.1.1" 33 | testCompile "com.github.brianPlummer:tinydancer-noop:0.1.1" 34 | compile project(path: ':observablerm') 35 | } 36 | -------------------------------------------------------------------------------- /app/src/main/res/menu/menu_action.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 13 | 16 | 17 | 20 | 21 | 24 | 25 | 28 | 29 | 32 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /observablerm/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: "me.tatarka.retrolambda" 3 | 4 | android { 5 | compileSdkVersion rootProject.ext.android["compileSdkVersion"] 6 | buildToolsVersion rootProject.ext.android["buildToolsVersion"] 7 | compileOptions { 8 | sourceCompatibility JavaVersion.VERSION_1_8 9 | targetCompatibility JavaVersion.VERSION_1_8 10 | } 11 | defaultConfig { 12 | minSdkVersion rootProject.ext.android["minSdkVersion"] 13 | targetSdkVersion rootProject.ext.android["targetSdkVersion"] 14 | versionCode rootProject.ext.android["versionCode"] 15 | versionName rootProject.ext.android["versionName"] 16 | } 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | } 24 | 25 | dependencies { 26 | compile fileTree(dir: 'libs', include: ['*.jar']) 27 | testCompile 'junit:junit:4.12' 28 | compile 'com.android.support:appcompat-v7:24.2.0' 29 | compile 'com.android.support:recyclerview-v7:24.2.0' 30 | compile 'io.reactivex:rxjava:1.1.9' 31 | compile('io.reactivex:rxandroid:1.2.1') { 32 | transitive = true 33 | } 34 | } 35 | 36 | apply from: "https://raw.githubusercontent.com/henrytao-me/bintray/master/installv1.gradle" 37 | apply from: "https://raw.githubusercontent.com/henrytao-me/bintray/master/bintrayv1.gradle" -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/App.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter; 2 | 3 | import com.codemonkeylabs.fpslibrary.FrameDataCallback; 4 | import com.codemonkeylabs.fpslibrary.TinyDancer; 5 | 6 | import android.app.Application; 7 | import android.util.Log; 8 | 9 | /** 10 | * Created by SILONG on 8/29/16. 11 | */ 12 | public class App extends Application { 13 | 14 | @Override 15 | public void onCreate() { 16 | super.onCreate(); 17 | // TinyDancer.create() 18 | // .show(this); 19 | 20 | //alternatively 21 | // TinyDancer.create() 22 | // .redFlagPercentage(.1f) // set red indicator for 10%....different from default 23 | // .startingXPosition(200) 24 | // .startingYPosition(600) 25 | // .show(this); 26 | 27 | //you can add a callback to get frame times and the calculated 28 | //number of dropped frames within that window 29 | TinyDancer.create() 30 | .addFrameDataCallback(new FrameDataCallback() { 31 | @Override 32 | public void doFrame(long previousFrameNS, long currentFrameNS, int droppedFrames) { 33 | //collect your stats here 34 | long renderTime = (currentFrameNS - previousFrameNS) / 1000000; 35 | if (renderTime > 35) { 36 | Log.d("App", "rendered frame:" + renderTime); 37 | } 38 | } 39 | }) 40 | .show(this); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /observablerm/src/main/java/me/silong/snappyadapter/SnappyDiffCallback.java: -------------------------------------------------------------------------------- 1 | package me.silong.snappyadapter; 2 | 3 | import android.support.v4.util.Pair; 4 | import android.support.v7.util.DiffUtil; 5 | 6 | class SnappyDiffCallback extends DiffUtil.Callback { 7 | 8 | private final RxSortedListCallback mCallback; 9 | 10 | private final D[] mNewData; 11 | 12 | private final D[] mOldData; 13 | 14 | private final int mOldDataLength; 15 | 16 | private final int mNewDataLength; 17 | 18 | SnappyDiffCallback(RxSortedListCallback callback, D[] oldData, D[] newData, int oldDataLength, int newDataLength) { 19 | mOldData = oldData; 20 | mNewData = newData; 21 | mCallback = callback; 22 | mOldDataLength = oldDataLength; 23 | mNewDataLength = newDataLength; 24 | } 25 | 26 | static Pair calculate(RxSortedListCallback callback, D[] oldData, D[] newData, 27 | int oldDataLength, int newDataLength) { 28 | return Pair.create(DiffUtil.calculateDiff(new SnappyDiffCallback<>(callback, oldData, newData, oldDataLength, newDataLength)), newData); 29 | } 30 | 31 | @Override 32 | public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { 33 | return mCallback.areContentsTheSame(mOldData[oldItemPosition], mNewData[newItemPosition]); 34 | } 35 | 36 | @Override 37 | public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { 38 | return mCallback.areItemsTheSame(mOldData[oldItemPosition], mNewData[newItemPosition]); 39 | } 40 | 41 | @Override 42 | public int getNewListSize() { 43 | return mNewDataLength; 44 | } 45 | 46 | @Override 47 | public int getOldListSize() { 48 | return mOldDataLength; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/model/DataFactory.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter.model; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import rx.Observable; 7 | import rx.android.schedulers.AndroidSchedulers; 8 | import rx.schedulers.Schedulers; 9 | 10 | /** 11 | * Created by SILONG on 8/28/16. 12 | */ 13 | public class DataFactory { 14 | 15 | public static final int CHUNK = 10; 16 | 17 | private DataFactory() { 18 | 19 | } 20 | 21 | public static Observable> fakeUsersToSet(int size) { 22 | return Observable.defer(() -> { 23 | List users = new ArrayList<>(size); 24 | for (int i = 0; i < size; i++) { 25 | int rand = (int) (Math.random() * 100000); 26 | users.add(new User("User_" + i, "User_" + rand, (int) (Math.random() * 30 + 20), 27 | Math.random() < 0.5 ? User.Gender.male : User.Gender.female)); 28 | } 29 | return Observable.just(users); 30 | }) 31 | .subscribeOn(Schedulers.computation()) 32 | .observeOn(AndroidSchedulers.mainThread()); 33 | } 34 | 35 | public static Observable> fakeUsersToAddOrUpdate(int begin, int size) { 36 | return Observable.defer(() -> { 37 | List users = new ArrayList<>(size); 38 | for (int i = begin; i < begin + size; i++) { 39 | int rand = (int) (Math.random() * 10000); 40 | users.add(new User("User_" + i, "User_" + rand, (int) (Math.random() * 30 + 20), 41 | Math.random() < 0.5 ? User.Gender.male : User.Gender.female)); 42 | } 43 | return Observable.just(users); 44 | }).subscribeOn(Schedulers.computation()) 45 | .observeOn(AndroidSchedulers.mainThread()); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.annotation.Nullable; 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.view.View; 8 | import android.widget.AdapterView; 9 | import android.widget.ArrayAdapter; 10 | import android.widget.ListView; 11 | 12 | /** 13 | * Created by SILONG on 8/28/16. 14 | */ 15 | public class MainActivity extends AppCompatActivity { 16 | 17 | @Override 18 | protected void onCreate(@Nullable Bundle savedInstanceState) { 19 | super.onCreate(savedInstanceState); 20 | setContentView(R.layout.activity_main); 21 | ListView listView = (ListView) findViewById(android.R.id.list); 22 | listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, 23 | new String[]{ 24 | "RxSortedList", 25 | "SortedList", 26 | "RegularList" 27 | })); 28 | listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 29 | @Override 30 | public void onItemClick(AdapterView adapterView, View view, int i, long l) { 31 | Intent intent; 32 | switch (i) { 33 | default: 34 | case 0: 35 | intent = RecyclerViewActivity.newRxSortedList(MainActivity.this, listView.getItemAtPosition(i).toString()); 36 | break; 37 | case 1: 38 | intent = RecyclerViewActivity.newSortedIntent(MainActivity.this, listView.getItemAtPosition(i).toString()); 39 | break; 40 | case 2: 41 | intent = RecyclerViewActivity.newRegularIntent(MainActivity.this, listView.getItemAtPosition(i).toString()); 42 | break; 43 | } 44 | startActivity(intent); 45 | } 46 | }); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /config.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 MySQUAR. All rights reserved. 3 | * 4 | * This software is the confidential and proprietary information of MySQUAR or one of its 5 | * subsidiaries. You shall not disclose this confidential information and shall use it only in 6 | * accordance with the terms of the license agreement or other applicable agreement you entered into 7 | * with MySQUAR. 8 | * 9 | * MySQUAR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER 10 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, 11 | * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. MySQUAR SHALL NOT BE LIABLE FOR ANY LOSSES 12 | * OR DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR 13 | * ITS DERIVATIVES. 14 | */ 15 | 16 | ext { 17 | 18 | android = [ 19 | compileSdkVersion: 24, 20 | buildToolsVersion: "24.0.1", 21 | applicationId : "me.silong.observablerm", 22 | minSdkVersion : 15, 23 | targetSdkVersion : 23, 24 | versionCode : 25, 25 | versionName : "1.0.0-beta" 26 | ] 27 | 28 | bintray = [ 29 | bintrayRepo : "maven", 30 | bintrayName : "observablerm", 31 | 32 | publishedGroupId : "me.silong", 33 | libraryName : "Observable RecyclerViewAdapter Manager", 34 | artifact : "observablerm", 35 | 36 | libraryDescription: "Observable RecyclerViewAdapter Manager", 37 | 38 | siteUrl : "https://github.com/longbkiter07/SnappyRecyclerAdapter/", 39 | gitUrl : "git@github.com:longbkiter07/SnappyRecyclerAdapter.git", 40 | 41 | libraryVersion : rootProject.ext.android["versionName"], 42 | 43 | developerId : "longbkiter07", 44 | developerName : "Si Long", 45 | developerEmail : "long.bkiter07@gmail.com", 46 | 47 | licenseName : "The Apache Software License, Version 2.0", 48 | licenseUrl : "http://www.apache.org/licenses/LICENSE-2.0.txt", 49 | allLicenses : ["Apache-2.0"] 50 | ] 51 | } 52 | -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/adapter/RxUserRecyclerViewAdapter.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter.adapter; 2 | 3 | 4 | import com.silong.snappyrecycleradapter.ItemViewHolder; 5 | import com.silong.snappyrecycleradapter.R; 6 | import com.silong.snappyrecycleradapter.model.User; 7 | 8 | import android.support.v7.widget.RecyclerView; 9 | import android.text.TextUtils; 10 | import android.view.LayoutInflater; 11 | import android.view.ViewGroup; 12 | 13 | import me.silong.snappyadapter.RxRecyclerViewCallback; 14 | import me.silong.snappyadapter.RxSortedList; 15 | 16 | 17 | /** 18 | * Created by SILONG on 8/28/16. 19 | */ 20 | public class RxUserRecyclerViewAdapter extends RecyclerView.Adapter { 21 | 22 | private final RxSortedList mUserRxSortedList; 23 | 24 | public RxUserRecyclerViewAdapter() { 25 | mUserRxSortedList = new RxSortedList<>(User.class, new RxRecyclerViewCallback(this) { 26 | @Override 27 | public boolean areContentsTheSame(User oldData, User newData) { 28 | return oldData.age == newData.age && oldData.gender == newData.gender && TextUtils.equals(oldData.name, newData.name); 29 | } 30 | 31 | @Override 32 | public boolean areItemsTheSame(User oldData, User newData) { 33 | return TextUtils.equals(oldData.id, newData.id); 34 | } 35 | 36 | @Override 37 | public int compare(User o1, User o2) { 38 | return o1.name.compareTo(o2.name); 39 | } 40 | }); 41 | } 42 | 43 | public static RxUserRecyclerViewAdapter newAdapter() { 44 | return new RxUserRecyclerViewAdapter(); 45 | } 46 | 47 | public RxSortedList getObservableAdapterManager() { 48 | return mUserRxSortedList; 49 | } 50 | 51 | @Override 52 | public int getItemCount() { 53 | return mUserRxSortedList.size(); 54 | } 55 | 56 | @Override 57 | public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 58 | return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false)); 59 | } 60 | 61 | @Override 62 | public void onBindViewHolder(ItemViewHolder holder, int position) { 63 | holder.bind(mUserRxSortedList.get(position)); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/adapter/SortedListRecyclerViewAdapter.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter.adapter; 2 | 3 | import com.silong.snappyrecycleradapter.ItemViewHolder; 4 | import com.silong.snappyrecycleradapter.R; 5 | import com.silong.snappyrecycleradapter.model.User; 6 | 7 | import android.support.v7.util.SortedList; 8 | import android.support.v7.widget.RecyclerView; 9 | import android.support.v7.widget.util.SortedListAdapterCallback; 10 | import android.text.TextUtils; 11 | import android.view.LayoutInflater; 12 | import android.view.ViewGroup; 13 | 14 | import java.util.List; 15 | 16 | 17 | public class SortedListRecyclerViewAdapter extends RecyclerView.Adapter implements SyncList { 18 | 19 | private SortedList mSortedList; 20 | 21 | public SortedListRecyclerViewAdapter() { 22 | mSortedList = new SortedList<>(User.class, new SortedListAdapterCallback(this) { 23 | 24 | @Override 25 | public boolean areContentsTheSame(User oldData, User newData) { 26 | return oldData.age == newData.age && oldData.gender == newData.gender && TextUtils.equals(oldData.name, newData.name); 27 | } 28 | 29 | @Override 30 | public boolean areItemsTheSame(User oldData, User newData) { 31 | return TextUtils.equals(oldData.id, newData.id); 32 | } 33 | 34 | @Override 35 | public int compare(User o1, User o2) { 36 | return o1.name.compareTo(o2.name); 37 | } 38 | }); 39 | } 40 | 41 | @Override 42 | public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 43 | return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false)); 44 | } 45 | 46 | @Override 47 | public void onBindViewHolder(ItemViewHolder holder, int position) { 48 | holder.bind(mSortedList.get(position)); 49 | } 50 | 51 | @Override 52 | public int getItemCount() { 53 | return mSortedList.size(); 54 | } 55 | 56 | public void add(User user) { 57 | long time = System.nanoTime(); 58 | mSortedList.add(user); 59 | } 60 | 61 | public void add(List users) { 62 | mSortedList.addAll(users); 63 | } 64 | 65 | public void remove(User user) { 66 | mSortedList.remove(user); 67 | } 68 | 69 | public void remove(int index) { 70 | mSortedList.removeItemAt(index); 71 | } 72 | 73 | public void clear() { 74 | mSortedList.clear(); 75 | } 76 | 77 | @Override 78 | public void set(User user, int pos) { 79 | mSortedList.updateItemAt(pos, user); 80 | } 81 | 82 | @Override 83 | public void set(List users) { 84 | mSortedList.clear(); 85 | mSortedList.addAll(users); 86 | } 87 | } -------------------------------------------------------------------------------- /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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 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 Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SnappyRecyclerAdapter 2 | 3 | This library helps you to manage `RecyclerViewAdapter` easier. This library is very useful for rendering a sorted data in real time (For example: chat application) 4 | 5 | # Features 6 | 7 | * Calling `notifyDataSetChanges`, `notifyItemInserted`, `notifyItemChanged`... automatically 8 | * Applying both `SortedList` and `DiffUtil` 9 | * Calling `DiffUtil` in background thread so that the ui does not lag 10 | * Queueing events to keep data is consistent. 11 | * Observable method so that we can catch the callback to do next action. 12 | 13 | # Usage 14 | 15 | This library requires RxJava / RxAndroid and AppCompat version 24.2.+(or newer) library to use. 16 | 17 | ``` 18 | compile 'io.reactivex:rxandroid:{lastest_version}' 19 | compile 'io.reactivex:rxjava:{lastest_version}' 20 | compile ('me.silong:observablerm:{latest_version}'){ 21 | transitive = true 22 | } 23 | compile 'com.android.support:appcompat-v7:24.+' 24 | compile 'com.android.support:recyclerview-v7:24.+' 25 | 26 | ``` 27 | 28 | Code example: please read sample app 29 | 30 | ## Create your RecyclerViewAdapter: 31 | 32 | ``` 33 | public class MyAdapter extends RecyclerViewAdapter { 34 | private final RxSortedList mRxSortedList; 35 | public MyRecyclerViewAdapter() { 36 | mRxSortedList = new RxSortedList<>(T.class, new RxRecyclerViewCallback(this) { 37 | @Override 38 | public boolean areContentsTheSame(T oldData, T newData) { 39 | return //return whether content of oldData and newData are the same 40 | } 41 | 42 | @Override 43 | public boolean areItemsTheSame(T oldData, T newData) { 44 | return //return whether oldData and newData are the same (checking object id is recommended) 45 | } 46 | 47 | @Override 48 | public int compare(T o1, T o2) { 49 | return //sort order. 50 | } 51 | }); 52 | } 53 | @Override 54 | public int getItemCount() { 55 | return mRxSortedList.size(); 56 | } 57 | ... 58 | } 59 | ``` 60 | 61 | ## Add item: 62 | 63 | ``` 64 | mObservableAdapterManager.add(item).subscribe(); 65 | ``` 66 | 67 | ## Add item with callback: 68 | 69 | ``` 70 | mObservableAdapterManager.add(item).subscribe(o -> { ... }, throwable -> { ... }); 71 | ``` 72 | 73 | The library also supports `remove`, `set`, `clear` method. 74 | 75 | # Issue 76 | 77 | Welcome everyone to discuss about this library [here] (https://github.com/longbkiter07/SnappyRecyclerAdapter/issues). 78 | 79 | # Thanks 80 | 81 | Thanks to [Henry](https://github.com/henrytao-me/) for deployment script. 82 | 83 | # License 84 | ``` 85 | Copyright(c) 2016 "Si Long " 86 | 87 | Licensed under the Apache License, Version 2.0 (the "License"); 88 | you may not use this file except in compliance with the License. 89 | You may obtain a copy of the License at 90 | 91 | http://www.apache.org/licenses/LICENSE-2.0 92 | 93 | Unless required by applicable law or agreed to in writing, software 94 | distributed under the License is distributed on an "AS IS" BASIS, 95 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 96 | See the License for the specific language governing permissions and 97 | limitations under the License. 98 | ``` 99 | -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/adapter/RegularRecyclerViewAdapter.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter.adapter; 2 | 3 | import com.silong.snappyrecycleradapter.ItemViewHolder; 4 | import com.silong.snappyrecycleradapter.R; 5 | import com.silong.snappyrecycleradapter.model.User; 6 | 7 | import android.support.v7.util.DiffUtil; 8 | import android.support.v7.widget.RecyclerView; 9 | import android.text.TextUtils; 10 | import android.view.LayoutInflater; 11 | import android.view.ViewGroup; 12 | 13 | import java.util.ArrayList; 14 | import java.util.Collections; 15 | import java.util.Comparator; 16 | import java.util.List; 17 | 18 | 19 | public class RegularRecyclerViewAdapter extends RecyclerView.Adapter implements SyncList { 20 | 21 | private List mUsers; 22 | 23 | public RegularRecyclerViewAdapter() { 24 | mUsers = new ArrayList<>(); 25 | } 26 | 27 | private void sortAndCallDiff(List oldList) { 28 | Collections.sort(mUsers, new Comparator() { 29 | @Override 30 | public int compare(User o1, User o2) { 31 | return o1.name.compareTo(o2.name); 32 | } 33 | }); 34 | DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffUtil.Callback() { 35 | @Override 36 | public int getOldListSize() { 37 | return mUsers.size(); 38 | } 39 | 40 | @Override 41 | public int getNewListSize() { 42 | return oldList.size(); 43 | } 44 | 45 | @Override 46 | public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { 47 | User oldData = mUsers.get(oldItemPosition); 48 | User newData = oldList.get(newItemPosition); 49 | return oldData.age == newData.age && oldData.gender == newData.gender && TextUtils.equals(oldData.name, newData.name); 50 | } 51 | 52 | @Override 53 | public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { 54 | User oldData = mUsers.get(oldItemPosition); 55 | User newData = oldList.get(newItemPosition); 56 | return TextUtils.equals(oldData.id, newData.id); 57 | } 58 | }); 59 | diffResult.dispatchUpdatesTo(this); 60 | } 61 | 62 | @Override 63 | public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 64 | return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false)); 65 | } 66 | 67 | @Override 68 | public void onBindViewHolder(ItemViewHolder holder, int position) { 69 | holder.bind(mUsers.get(position)); 70 | } 71 | 72 | @Override 73 | public int getItemCount() { 74 | return mUsers.size(); 75 | } 76 | 77 | public void add(User user) { 78 | List oldList = new ArrayList<>(mUsers); 79 | mUsers.add(user); 80 | sortAndCallDiff(oldList); 81 | } 82 | 83 | public void add(List users) { 84 | List oldList = new ArrayList<>(mUsers); 85 | mUsers.addAll(users); 86 | sortAndCallDiff(oldList); 87 | } 88 | 89 | public void remove(User user) { 90 | List oldList = new ArrayList<>(mUsers); 91 | mUsers.remove(user); 92 | sortAndCallDiff(oldList); 93 | } 94 | 95 | public void remove(int index) { 96 | List oldList = new ArrayList<>(mUsers); 97 | mUsers.remove(index); 98 | sortAndCallDiff(oldList); 99 | } 100 | 101 | public void clear() { 102 | int oldSize = mUsers.size(); 103 | mUsers.clear(); 104 | notifyItemRangeRemoved(0, oldSize); 105 | } 106 | 107 | @Override 108 | public void set(User user, int pos) { 109 | List oldList = new ArrayList<>(mUsers); 110 | mUsers.set(pos, user); 111 | sortAndCallDiff(oldList); 112 | } 113 | 114 | @Override 115 | public void set(List users) { 116 | List oldList = new ArrayList<>(mUsers); 117 | mUsers.clear(); 118 | mUsers.addAll(users); 119 | sortAndCallDiff(oldList); 120 | } 121 | } -------------------------------------------------------------------------------- /observablerm/src/main/java/me/silong/snappyadapter/RxSortedList.java: -------------------------------------------------------------------------------- 1 | package me.silong.snappyadapter; 2 | 3 | import java.util.Collection; 4 | import java.util.concurrent.Executor; 5 | import java.util.concurrent.Executors; 6 | 7 | import rx.Observable; 8 | import rx.android.schedulers.AndroidSchedulers; 9 | import rx.schedulers.Schedulers; 10 | 11 | /** 12 | * Created by SILONG on 4/21/17. 13 | */ 14 | 15 | public class RxSortedList { 16 | 17 | private static Executor sExecutor = Executors.newSingleThreadExecutor(); 18 | 19 | private SnappySortedList mSnappySortedList; 20 | 21 | public RxSortedList(Class klass, RxSortedListCallback callback) { 22 | mSnappySortedList = new SnappySortedList(klass, callback); 23 | } 24 | 25 | public RxSortedList(Class klass, RxSortedListCallback callback, int initialCapacity) { 26 | mSnappySortedList = new SnappySortedList(klass, callback); 27 | } 28 | 29 | private Observable.Transformer queueEvent() { 30 | return dObservable -> Observable.just(null) 31 | .subscribeOn(Schedulers.from(sExecutor)) 32 | .observeOn(AndroidSchedulers.mainThread()) 33 | .flatMap(o -> dObservable); 34 | } 35 | 36 | public int size() { 37 | return mSnappySortedList.size(); 38 | } 39 | 40 | public Observable add(T item) { 41 | return Observable.fromCallable(() -> mSnappySortedList.add(item)) 42 | .compose(queueEvent()); 43 | } 44 | 45 | public Observable addAll(T[] items, boolean mayModifyInput) { 46 | return Observable.fromCallable(() -> { 47 | mSnappySortedList.addAll(items, mayModifyInput); 48 | return null; 49 | }) 50 | .compose(queueEvent()); 51 | } 52 | 53 | public Observable addAll(T[] items) { 54 | return Observable.fromCallable(() -> { 55 | mSnappySortedList.addAll(items); 56 | return null; 57 | }) 58 | .compose(queueEvent()); 59 | } 60 | 61 | public Observable addAll(Collection items) { 62 | return Observable.fromCallable(() -> { 63 | mSnappySortedList.addAll(items); 64 | return null; 65 | }).compose(queueEvent()); 66 | } 67 | 68 | public void beginBatchedUpdates() { 69 | mSnappySortedList.beginBatchedUpdates(); 70 | } 71 | 72 | public void endBatchedUpdates() { 73 | mSnappySortedList.endBatchedUpdates(); 74 | } 75 | 76 | public Observable remove(T item) { 77 | return Observable.fromCallable(() -> mSnappySortedList.remove(item)).compose(queueEvent()); 78 | } 79 | 80 | public Observable removeItemAt(int index) { 81 | return Observable.fromCallable(() -> mSnappySortedList.removeItemAt(index)).compose(queueEvent()); 82 | } 83 | 84 | public Observable updateItemAt(int index, T item) { 85 | return Observable.fromCallable(() -> { 86 | mSnappySortedList.updateItemAt(index, item); 87 | return null; 88 | }).compose(queueEvent()); 89 | } 90 | 91 | 92 | public Observable recalculatePositionOfItemAt(int index) { 93 | return Observable.fromCallable(() -> { 94 | mSnappySortedList.recalculatePositionOfItemAt(index); 95 | return null; 96 | }).compose(queueEvent()); 97 | } 98 | 99 | 100 | public T get(int index) throws IndexOutOfBoundsException { 101 | return mSnappySortedList.get(index); 102 | } 103 | 104 | public Observable indexOf(T item) { 105 | return Observable.fromCallable(() -> mSnappySortedList.indexOf(item)).compose(queueEvent()); 106 | } 107 | 108 | public Observable clear() { 109 | return Observable.fromCallable(() -> { 110 | mSnappySortedList.clear(); 111 | return null; 112 | }).compose(queueEvent()); 113 | } 114 | 115 | public Observable set(Collection items, boolean isSorted) { 116 | return mSnappySortedList.set(items, isSorted) 117 | .subscribeOn(Schedulers.from(sExecutor)); 118 | } 119 | 120 | public Observable set(Collection items) { 121 | return mSnappySortedList.set(items) 122 | .subscribeOn(Schedulers.from(sExecutor)); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /observablerm/src/main/java/me/silong/snappyadapter/RxSortedListCallback.java: -------------------------------------------------------------------------------- 1 | package me.silong.snappyadapter; 2 | 3 | import android.support.v7.util.BatchingListUpdateCallback; 4 | import android.support.v7.util.ListUpdateCallback; 5 | 6 | import java.util.Comparator; 7 | 8 | /** 9 | * The class that controls the behavior of the {@link me.silong.snappyadapter.RxSortedList}. 10 | *

11 | * It defines how items should be sorted and how duplicates should be handled. 12 | *

13 | * SortedList calls the callback methods on this class to notify changes about the underlying 14 | * data. 15 | */ 16 | public abstract class RxSortedListCallback implements Comparator, ListUpdateCallback { 17 | 18 | /** 19 | * Similar to {@link java.util.Comparator#compare(Object, Object)}, should compare two and 20 | * return how they should be ordered. 21 | * 22 | * @param o1 The first object to compare. 23 | * @param o2 The second object to compare. 24 | * @return a negative integer, zero, or a positive integer as the 25 | * first argument is less than, equal to, or greater than the 26 | * second. 27 | */ 28 | @Override 29 | abstract public int compare(T2 o1, T2 o2); 30 | 31 | /** 32 | * Called by the SortedList when the item at the given position is updated. 33 | * 34 | * @param position The position of the item which has been updated. 35 | * @param count The number of items which has changed. 36 | */ 37 | abstract public void onChanged(int position, int count); 38 | 39 | @Override 40 | public void onChanged(int position, int count, Object payload) { 41 | onChanged(position, count); 42 | } 43 | 44 | /** 45 | * Called by the SortedList when it wants to check whether two items have the same data 46 | * or not. SortedList uses this information to decide whether it should call 47 | * {@link #onChanged(int, int)} or not. 48 | *

49 | * SortedList uses this method to check equality instead of {@link Object#equals(Object)} 50 | * so 51 | * that you can change its behavior depending on your UI. 52 | *

53 | * For example, if you are using SortedList with a RecyclerView.Adapter, you should 54 | * return whether the items' visual representations are the same or not. 55 | * 56 | * @param oldItem The previous representation of the object. 57 | * @param newItem The new object that replaces the previous one. 58 | * @return True if the contents of the items are the same or false if they are different. 59 | */ 60 | abstract public boolean areContentsTheSame(T2 oldItem, T2 newItem); 61 | 62 | /** 63 | * Called by the SortedList to decide whether two object represent the same Item or not. 64 | *

65 | * For example, if your items have unique ids, this method should check their equality. 66 | * 67 | * @param item1 The first item to check. 68 | * @param item2 The second item to check. 69 | * @return True if the two items represent the same object or false if they are different. 70 | */ 71 | abstract public boolean areItemsTheSame(T2 item1, T2 item2); 72 | 73 | /** 74 | * A callback implementation that can batch notify events dispatched by the SortedList. 75 | *

76 | * This class can be useful if you want to do multiple operations on a SortedList but don't 77 | * want to dispatch each event one by one, which may result in a performance issue. 78 | *

79 | * For example, if you are going to add multiple items to a SortedList, BatchedCallback call 80 | * convert individual onInserted(index, 1) calls into one 81 | * onInserted(index, N) if items are added into consecutive indices. This change 82 | * can help RecyclerView resolve changes much more easily. 83 | *

84 | * If consecutive changes in the SortedList are not suitable for batching, BatchingCallback 85 | * dispatches them as soon as such case is detected. After your edits on the SortedList is 86 | * complete, you must always call {@link me.silong.snappyadapter.RxSortedListCallback.BatchedCallback#dispatchLastEvent()} to flush 87 | * all changes to the Callback. 88 | */ 89 | public static final class BatchedCallback extends RxSortedListCallback { 90 | 91 | final RxSortedListCallback mWrappedCallback; 92 | 93 | final BatchingListUpdateCallback mBatchingListUpdateCallback; 94 | 95 | /** 96 | * Creates a new BatchedCallback that wraps the provided Callback. 97 | * 98 | * @param wrappedCallback The Callback which should received the data change callbacks. 99 | * Other method calls (e.g. {@link #compare(Object, Object)} from 100 | * the SortedList are directly forwarded to this Callback. 101 | */ 102 | public BatchedCallback(RxSortedListCallback wrappedCallback) { 103 | mWrappedCallback = wrappedCallback; 104 | mBatchingListUpdateCallback = new BatchingListUpdateCallback(mWrappedCallback); 105 | } 106 | 107 | @Override 108 | public int compare(T2 o1, T2 o2) { 109 | return mWrappedCallback.compare(o1, o2); 110 | } 111 | 112 | @Override 113 | public void onInserted(int position, int count) { 114 | mBatchingListUpdateCallback.onInserted(position, count); 115 | } 116 | 117 | @Override 118 | public void onRemoved(int position, int count) { 119 | mBatchingListUpdateCallback.onRemoved(position, count); 120 | } 121 | 122 | @Override 123 | public void onMoved(int fromPosition, int toPosition) { 124 | mBatchingListUpdateCallback.onInserted(fromPosition, toPosition); 125 | } 126 | 127 | @Override 128 | public void onChanged(int position, int count) { 129 | mBatchingListUpdateCallback.onChanged(position, count, null); 130 | } 131 | 132 | @Override 133 | public boolean areContentsTheSame(T2 oldItem, T2 newItem) { 134 | return mWrappedCallback.areContentsTheSame(oldItem, newItem); 135 | } 136 | 137 | @Override 138 | public boolean areItemsTheSame(T2 item1, T2 item2) { 139 | return mWrappedCallback.areItemsTheSame(item1, item2); 140 | } 141 | 142 | /** 143 | * This method dispatches any pending event notifications to the wrapped Callback. 144 | * You must always call this method after you are done with editing the SortedList. 145 | */ 146 | public void dispatchLastEvent() { 147 | mBatchingListUpdateCallback.dispatchLastEvent(); 148 | } 149 | } 150 | } -------------------------------------------------------------------------------- /observablerm/src/test/java/me/silong/observablerm/ObservableAdapterManagerTest.java: -------------------------------------------------------------------------------- 1 | package me.silong.observablerm; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.concurrent.Executors; 9 | import java.util.concurrent.TimeUnit; 10 | 11 | import rx.Observable; 12 | import rx.Scheduler; 13 | import rx.Subscriber; 14 | import rx.Subscription; 15 | import rx.android.plugins.RxAndroidPlugins; 16 | import rx.android.plugins.RxAndroidSchedulersHook; 17 | import rx.schedulers.Schedulers; 18 | 19 | /** 20 | * Created by SILONG on 11/3/16. 21 | */ 22 | public class ObservableAdapterManagerTest { 23 | 24 | private static List generateTestData(int count) { 25 | List testDatas = new ArrayList<>(count); 26 | for (int i = 0; i < count; i++) { 27 | testDatas.add(new TestData("id" + i, "name" + i)); 28 | } 29 | return testDatas; 30 | } 31 | 32 | @Before 33 | public void setup() { 34 | RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() { 35 | @Override 36 | public Scheduler getMainThreadScheduler() { 37 | return Schedulers.from(Executors.newSingleThreadExecutor()); 38 | } 39 | }); 40 | } 41 | 42 | @Test 43 | public void testScheduler() throws Exception { 44 | Scheduler scheduler = Schedulers.newThread(); 45 | Subscription subscription = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler) 46 | .doOnNext(aLong -> System.out.println("onNext 1:" + aLong)) 47 | .map(aLong -> { 48 | for (int i = 0; i < 100000000; i++) { 49 | aLong += i; 50 | aLong ^= i; 51 | } 52 | return aLong; 53 | }) 54 | .doOnNext(aLong -> System.out.println("onNext 2:" + aLong + "-" + System.currentTimeMillis() / 1000)) 55 | .subscribeOn(scheduler) 56 | .doOnTerminate(() -> System.out.println("terminated")) 57 | .doOnUnsubscribe(() -> System.out.println("unsubscribed-" + System.currentTimeMillis() / 1000)) 58 | .doOnCompleted(() -> System.out.println("completed-" + System.currentTimeMillis() / 1000)) 59 | .subscribe(new Subscriber() { 60 | @Override 61 | public void onCompleted() { 62 | 63 | } 64 | 65 | @Override 66 | public void onError(Throwable e) { 67 | 68 | } 69 | 70 | @Override 71 | public void onNext(Long aLong) { 72 | if (!isUnsubscribed()) { 73 | System.out.println("onNext event 1:" + aLong); 74 | } 75 | System.out.println("onNext event 2:" + aLong); 76 | } 77 | }); 78 | Thread.sleep(3200); 79 | subscription.unsubscribe(); 80 | Thread.sleep(2000); 81 | } 82 | 83 | @Test(timeout = 5000) 84 | public void testQueueingEvent() throws Exception { 85 | // ObservableAdapterManager observableAdapterManager = new ObservableAdapterManager(null, new ArrayList<>(), 86 | // new DataComparable() { 87 | // @Override 88 | // public boolean areContentsTheSame(TestData oldData, TestData newData) { 89 | // return oldData.name.equals(newData.name); 90 | // } 91 | // 92 | // @Override 93 | // public boolean areItemsTheSame(TestData oldData, TestData newData) { 94 | // return oldData.id.equals(newData.id); 95 | // } 96 | // }); 97 | // PublishSubject> subject = PublishSubject.create(); 98 | // TestSubscriber testSubscriber = new TestSubscriber<>(); 99 | // subject 100 | // .flatMap(testData -> observableAdapterManager.setItems(testData)) 101 | // .subscribe(testSubscriber); 102 | // subject.onNext(generateTestData(100)); 103 | // Thread.sleep(5); 104 | // subject.onNext(generateTestData(0)); 105 | // Thread.sleep(5); 106 | // subject.onNext(generateTestData(101)); 107 | // Thread.sleep(5); 108 | // subject.onNext(generateTestData(0)); 109 | // Thread.sleep(5); 110 | // subject.onNext(generateTestData(102)); 111 | // Thread.sleep(5); 112 | // subject.onNext(generateTestData(0)); 113 | // Thread.sleep(5); 114 | // subject.onNext(generateTestData(200)); 115 | // Thread.sleep(5); 116 | // subject.onNext(generateTestData(0)); 117 | // Thread.sleep(5); 118 | // subject.onNext(generateTestData(201)); 119 | // subject.onNext(generateTestData(200)); 120 | // Thread.sleep(5); 121 | // subject.onNext(generateTestData(0)); 122 | // Thread.sleep(5); 123 | // subject.onNext(generateTestData(201)); 124 | // subject.onNext(generateTestData(200)); 125 | // Thread.sleep(5); 126 | // subject.onNext(generateTestData(0)); 127 | // Thread.sleep(5); 128 | // subject.onNext(generateTestData(201)); 129 | // Thread.sleep(2000); 130 | // // subject.onCompleted(); 131 | // // testSubscriber.awaitTerminalEvent(); 132 | // assertThat(testSubscriber.getOnNextEvents().size(), equalTo(15)); 133 | } 134 | 135 | @Test(timeout = 5000) 136 | public void testClearData() throws Exception { 137 | // ObservableAdapterManager observableAdapterManager = new ObservableAdapterManager(null, new ArrayList<>(), 138 | // new DataComparable() { 139 | // @Override 140 | // public boolean areContentsTheSame(TestData oldData, TestData newData) { 141 | // return oldData.name.equals(newData.name); 142 | // } 143 | // 144 | // @Override 145 | // public boolean areItemsTheSame(TestData oldData, TestData newData) { 146 | // return oldData.id.equals(newData.id); 147 | // } 148 | // }); 149 | // PublishSubject> subject = PublishSubject.create(); 150 | // TestSubscriber testSubscriber = new TestSubscriber<>(); 151 | // subject 152 | // .flatMap(testData -> observableAdapterManager.setItems(testData)) 153 | // .doOnNext(aVoid -> System.out.println("onNext event")) 154 | // .doOnUnsubscribe(() -> System.out.println("onUnsubscribed")) 155 | // .subscribe(testSubscriber); 156 | // subject.onNext(generateTestData(100)); 157 | // subject.onNext(generateTestData(0)); 158 | // subject.onNext(generateTestData(101)); 159 | // subject.onNext(generateTestData(0)); 160 | // subject.onNext(generateTestData(102)); 161 | // subject.onNext(generateTestData(0)); 162 | // subject.onNext(generateTestData(200)); 163 | // subject.onNext(generateTestData(0)); 164 | // subject.onNext(generateTestData(201)); 165 | // subject.onNext(generateTestData(200)); 166 | // subject.onNext(generateTestData(0)); 167 | // subject.onNext(generateTestData(201)); 168 | // subject.onNext(generateTestData(200)); 169 | // subject.onNext(generateTestData(0)); 170 | // subject.onNext(generateTestData(201)); 171 | // Thread.sleep(15); 172 | // observableAdapterManager.clearEvents(); 173 | // Thread.sleep(2000); 174 | // System.out.println("event count:" + testSubscriber.getValueCount()); 175 | } 176 | 177 | private static class TestData { 178 | 179 | String id; 180 | 181 | String name; 182 | 183 | public TestData(String id, String name) { 184 | this.id = id; 185 | this.name = name; 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /app/src/main/java/com/silong/snappyrecycleradapter/RecyclerViewActivity.java: -------------------------------------------------------------------------------- 1 | package com.silong.snappyrecycleradapter; 2 | 3 | import com.silong.snappyrecycleradapter.adapter.RegularRecyclerViewAdapter; 4 | import com.silong.snappyrecycleradapter.adapter.RxUserRecyclerViewAdapter; 5 | import com.silong.snappyrecycleradapter.adapter.SortedListRecyclerViewAdapter; 6 | import com.silong.snappyrecycleradapter.adapter.SyncList; 7 | import com.silong.snappyrecycleradapter.model.DataFactory; 8 | import com.silong.snappyrecycleradapter.model.User; 9 | 10 | import android.content.Context; 11 | import android.content.Intent; 12 | import android.os.Bundle; 13 | import android.support.annotation.Nullable; 14 | import android.support.v7.app.AppCompatActivity; 15 | import android.support.v7.widget.LinearLayoutManager; 16 | import android.support.v7.widget.RecyclerView; 17 | import android.view.Menu; 18 | import android.view.MenuItem; 19 | 20 | 21 | /** 22 | * Created by SILONG on 8/28/16. 23 | */ 24 | public class RecyclerViewActivity extends AppCompatActivity { 25 | 26 | private static final String MODE = "mode"; 27 | 28 | private static final int MODE_REGULAR = 2; 29 | 30 | private static final int MODE_SORTED_LIST = 1; 31 | 32 | private static final int MODE_RXSORTED_LIST = 0; 33 | 34 | private RxUserRecyclerViewAdapter mRxUserRecyclerViewAdapter; 35 | 36 | private SyncList mSyncAdapter; 37 | 38 | public static Intent newRxSortedList(Context context, String name) { 39 | Intent intent = new Intent(context, RecyclerViewActivity.class); 40 | intent.putExtra(MODE, MODE_RXSORTED_LIST); 41 | intent.putExtra("name", name); 42 | return intent; 43 | } 44 | 45 | public static Intent newSortedIntent(Context context, String name) { 46 | Intent intent = new Intent(context, RecyclerViewActivity.class); 47 | intent.putExtra(MODE, MODE_SORTED_LIST); 48 | intent.putExtra("name", name); 49 | return intent; 50 | } 51 | 52 | public static Intent newRegularIntent(Context context, String name) { 53 | Intent intent = new Intent(context, RecyclerViewActivity.class); 54 | intent.putExtra(MODE, MODE_REGULAR); 55 | intent.putExtra("name", name); 56 | return intent; 57 | } 58 | 59 | @Override 60 | protected void onCreate(@Nullable Bundle savedInstanceState) { 61 | super.onCreate(savedInstanceState); 62 | setTitle(getIntent().getStringExtra("name")); 63 | RecyclerView recyclerView = new RecyclerView(this); 64 | setContentView(recyclerView); 65 | recyclerView.setLayoutManager(new LinearLayoutManager(this)); 66 | int mode = getIntent().getIntExtra(MODE, MODE_REGULAR); 67 | DataFactory.fakeUsersToSet(DataFactory.CHUNK).subscribe(users -> { 68 | switch (mode) { 69 | case MODE_REGULAR: 70 | RegularRecyclerViewAdapter regularRecyclerViewAdapter = new RegularRecyclerViewAdapter(); 71 | mSyncAdapter = regularRecyclerViewAdapter; 72 | mSyncAdapter.set(users); 73 | recyclerView.setAdapter(regularRecyclerViewAdapter); 74 | break; 75 | case MODE_SORTED_LIST: 76 | SortedListRecyclerViewAdapter sortedListRecyclerViewAdapter = new SortedListRecyclerViewAdapter(); 77 | mSyncAdapter = sortedListRecyclerViewAdapter; 78 | mSyncAdapter.set(users); 79 | recyclerView.setAdapter(sortedListRecyclerViewAdapter); 80 | break; 81 | case MODE_RXSORTED_LIST: 82 | mRxUserRecyclerViewAdapter = RxUserRecyclerViewAdapter.newAdapter(); 83 | mRxUserRecyclerViewAdapter.getObservableAdapterManager().set(users).subscribe(); 84 | recyclerView.setAdapter(mRxUserRecyclerViewAdapter); 85 | break; 86 | } 87 | }); 88 | } 89 | 90 | @Override 91 | public boolean onOptionsItemSelected(MenuItem item) { 92 | switch (item.getItemId()) { 93 | case R.id.action_add_multi: 94 | if (mSyncAdapter != null) { 95 | DataFactory.fakeUsersToAddOrUpdate(mSyncAdapter.getItemCount(), DataFactory.CHUNK) 96 | .subscribe(users -> { 97 | mSyncAdapter.add(users); 98 | }); 99 | } else { 100 | DataFactory.fakeUsersToAddOrUpdate(mRxUserRecyclerViewAdapter.getItemCount(), DataFactory.CHUNK) 101 | .flatMap(users -> mRxUserRecyclerViewAdapter.getObservableAdapterManager().addAll(users)) 102 | .subscribe(); 103 | } 104 | break; 105 | case R.id.action_add_multi_at_specific_index: 106 | if (mSyncAdapter != null) { 107 | DataFactory.fakeUsersToAddOrUpdate(mSyncAdapter.getItemCount(), DataFactory.CHUNK) 108 | .subscribe(users -> { 109 | mSyncAdapter 110 | .add(users); 111 | }); 112 | } else { 113 | DataFactory.fakeUsersToAddOrUpdate(mRxUserRecyclerViewAdapter.getItemCount(), DataFactory.CHUNK) 114 | .flatMap(users -> mRxUserRecyclerViewAdapter.getObservableAdapterManager() 115 | .addAll(users)) 116 | .subscribe(); 117 | } 118 | break; 119 | case R.id.action_add_single: 120 | if (mSyncAdapter != null) { 121 | DataFactory.fakeUsersToAddOrUpdate(mSyncAdapter.getItemCount(), 1) 122 | .subscribe(users -> { 123 | mSyncAdapter.add(users.get(0)); 124 | }); 125 | } else { 126 | DataFactory.fakeUsersToAddOrUpdate(mRxUserRecyclerViewAdapter.getItemCount(), 1) 127 | .map(users -> users.get(0)) 128 | .flatMap(user -> mRxUserRecyclerViewAdapter.getObservableAdapterManager() 129 | .add(user)) 130 | .subscribe(); 131 | } 132 | break; 133 | case R.id.action_clear: 134 | if (mSyncAdapter != null) { 135 | mSyncAdapter.clear(); 136 | } else { 137 | mRxUserRecyclerViewAdapter.getObservableAdapterManager().clear().subscribe(); 138 | } 139 | break; 140 | case R.id.action_remove_one_item: 141 | if (mSyncAdapter != null) { 142 | mSyncAdapter.remove((int) (Math.random() * mSyncAdapter.getItemCount() - 1)); 143 | } else { 144 | mRxUserRecyclerViewAdapter.getObservableAdapterManager() 145 | .removeItemAt((int) (Math.random() * mRxUserRecyclerViewAdapter.getItemCount() - 1)) 146 | .subscribe(); 147 | } 148 | break; 149 | case R.id.action_set_items: 150 | if (mSyncAdapter != null) { 151 | DataFactory.fakeUsersToSet(DataFactory.CHUNK) 152 | .subscribe(users -> { 153 | mSyncAdapter.set(users); 154 | }); 155 | } else { 156 | DataFactory.fakeUsersToSet(DataFactory.CHUNK) 157 | .flatMap(users -> mRxUserRecyclerViewAdapter.getObservableAdapterManager().set(users)) 158 | .subscribe(); 159 | } 160 | break; 161 | case R.id.action_set_one_item: 162 | int i = (int) (Math.random() * 100); 163 | if (mSyncAdapter != null) { 164 | mSyncAdapter.set(new User("User_" + i, "custom_name " + Math.random(), 100, User.Gender.male), 165 | (int) (Math.random() * mSyncAdapter.getItemCount() - 1)); 166 | } else { 167 | mRxUserRecyclerViewAdapter.getObservableAdapterManager().updateItemAt( 168 | (int) (Math.random() * mRxUserRecyclerViewAdapter.getItemCount() - 1), 169 | new User("User_" + i, "custom_name" + Math.random(), 100, User.Gender.male)).subscribe(); 170 | } 171 | break; 172 | } 173 | return super.onOptionsItemSelected(item); 174 | } 175 | 176 | @Override 177 | public boolean onCreateOptionsMenu(Menu menu) { 178 | getMenuInflater().inflate(R.menu.menu_action, menu); 179 | return super.onCreateOptionsMenu(menu); 180 | } 181 | 182 | } 183 | -------------------------------------------------------------------------------- /observablerm/src/main/java/me/silong/snappyadapter/SnappySortedList.java: -------------------------------------------------------------------------------- 1 | package me.silong.snappyadapter; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.Arrays; 5 | import java.util.Collection; 6 | 7 | import rx.Observable; 8 | import rx.android.schedulers.AndroidSchedulers; 9 | 10 | /** 11 | * Created by SILONG on 4/20/17. 12 | */ 13 | 14 | class SnappySortedList { 15 | 16 | /** 17 | * Used by {@link #indexOf(Object)} when he item cannot be found in the list. 18 | */ 19 | public static final int INVALID_POSITION = -1; 20 | 21 | private static final int MIN_CAPACITY = 10; 22 | 23 | private static final int CAPACITY_GROWTH = MIN_CAPACITY; 24 | 25 | private static final int INSERTION = 1; 26 | 27 | private static final int DELETION = 1 << 1; 28 | 29 | private static final int LOOKUP = 1 << 2; 30 | 31 | private final Class mTClass; 32 | 33 | T[] mData; 34 | 35 | private T[] mOldData; 36 | 37 | private int mOldDataStart; 38 | 39 | private int mOldDataSize; 40 | 41 | private int mMergedSize; 42 | 43 | private RxSortedListCallback mCallback; 44 | 45 | private RxSortedListCallback.BatchedCallback mBatchedCallback; 46 | 47 | private int mSize; 48 | 49 | public SnappySortedList(Class klass, RxSortedListCallback callback) { 50 | this(klass, callback, MIN_CAPACITY); 51 | } 52 | 53 | public SnappySortedList(Class klass, RxSortedListCallback callback, int initialCapacity) { 54 | mTClass = klass; 55 | mData = (T[]) Array.newInstance(klass, initialCapacity); 56 | mCallback = callback; 57 | mSize = 0; 58 | } 59 | 60 | public int size() { 61 | return mSize; 62 | } 63 | 64 | public int add(T item) { 65 | throwIfMerging(); 66 | return add(item, true); 67 | } 68 | 69 | public void addAll(T[] items, boolean mayModifyInput) { 70 | throwIfMerging(); 71 | if (items.length == 0) { 72 | return; 73 | } 74 | if (mayModifyInput) { 75 | addAllInternal(items); 76 | } else { 77 | T[] copy = (T[]) Array.newInstance(mTClass, items.length); 78 | System.arraycopy(items, 0, copy, 0, items.length); 79 | addAllInternal(copy); 80 | } 81 | 82 | } 83 | 84 | public void addAll(T... items) { 85 | addAll(items, false); 86 | } 87 | 88 | public void addAll(Collection items) { 89 | T[] copy = (T[]) Array.newInstance(mTClass, items.size()); 90 | addAll(items.toArray(copy), true); 91 | } 92 | 93 | public Observable set(Collection items) { 94 | return set(items, false); 95 | } 96 | 97 | public Observable set(Collection items, boolean isSorted) { 98 | return Observable.fromCallable(() -> { 99 | T[] newItems = (T[]) Array.newInstance(mTClass, items.size()); 100 | T[] oldItems = (T[]) Array.newInstance(mTClass, mData.length); 101 | System.arraycopy(mData, 0, oldItems, 0, mData.length); 102 | items.toArray(newItems); 103 | if (!isSorted) { 104 | Arrays.sort(newItems, mCallback); 105 | } 106 | return SnappyDiffCallback.calculate(mCallback, oldItems, newItems, mSize, items.size()); 107 | }) 108 | .observeOn(AndroidSchedulers.mainThread()) 109 | .map(diffResultPair -> { 110 | mData = diffResultPair.second; 111 | mSize = diffResultPair.second.length; 112 | diffResultPair.first.dispatchUpdatesTo(mCallback); 113 | return null; 114 | }); 115 | } 116 | 117 | private void addAllInternal(T[] newItems) { 118 | final boolean forceBatchedUpdates = !(mCallback instanceof RxSortedListCallback.BatchedCallback); 119 | if (forceBatchedUpdates) { 120 | beginBatchedUpdates(); 121 | } 122 | 123 | mOldData = mData; 124 | mOldDataStart = 0; 125 | mOldDataSize = mSize; 126 | 127 | Arrays.sort(newItems, mCallback); // Arrays.sort is stable. 128 | 129 | final int newSize = deduplicate(newItems); 130 | if (mSize == 0) { 131 | mData = newItems; 132 | mSize = newSize; 133 | mMergedSize = newSize; 134 | mCallback.onInserted(0, newSize); 135 | } else { 136 | merge(newItems, newSize); 137 | } 138 | 139 | mOldData = null; 140 | 141 | if (forceBatchedUpdates) { 142 | endBatchedUpdates(); 143 | } 144 | } 145 | 146 | private int deduplicate(T[] items) { 147 | if (items.length == 0) { 148 | throw new IllegalArgumentException("Input array must be non-empty"); 149 | } 150 | 151 | // Keep track of the range of equal items at the end of the output. 152 | // Start with the range containing just the first item. 153 | int rangeStart = 0; 154 | int rangeEnd = 1; 155 | 156 | for (int i = 1; i < items.length; ++i) { 157 | T currentItem = items[i]; 158 | 159 | int compare = mCallback.compare(items[rangeStart], currentItem); 160 | if (compare > 0) { 161 | throw new IllegalArgumentException("Input must be sorted in ascending order."); 162 | } 163 | 164 | if (compare == 0) { 165 | // The range of equal items continues, update it. 166 | final int sameItemPos = findSameItem(currentItem, items, rangeStart, rangeEnd); 167 | if (sameItemPos != INVALID_POSITION) { 168 | // Replace the duplicate item. 169 | items[sameItemPos] = currentItem; 170 | } else { 171 | // Expand the range. 172 | if (rangeEnd != i) { // Avoid redundant copy. 173 | items[rangeEnd] = currentItem; 174 | } 175 | rangeEnd++; 176 | } 177 | } else { 178 | // The range has ended. Reset it to contain just the current item. 179 | if (rangeEnd != i) { // Avoid redundant copy. 180 | items[rangeEnd] = currentItem; 181 | } 182 | rangeStart = rangeEnd++; 183 | } 184 | } 185 | return rangeEnd; 186 | } 187 | 188 | 189 | private int findSameItem(T item, T[] items, int from, int to) { 190 | for (int pos = from; pos < to; pos++) { 191 | if (mCallback.areItemsTheSame(items[pos], item)) { 192 | return pos; 193 | } 194 | } 195 | return INVALID_POSITION; 196 | } 197 | 198 | /** 199 | * This method assumes that newItems are sorted and deduplicated. 200 | */ 201 | private void merge(T[] newData, int newDataSize) { 202 | final int mergedCapacity = mSize + newDataSize + CAPACITY_GROWTH; 203 | mData = (T[]) Array.newInstance(mTClass, mergedCapacity); 204 | mMergedSize = 0; 205 | 206 | int newDataStart = 0; 207 | while (mOldDataStart < mOldDataSize || newDataStart < newDataSize) { 208 | if (mOldDataStart == mOldDataSize) { 209 | // No more old items, copy the remaining new items. 210 | int itemCount = newDataSize - newDataStart; 211 | System.arraycopy(newData, newDataStart, mData, mMergedSize, itemCount); 212 | mMergedSize += itemCount; 213 | mSize += itemCount; 214 | mCallback.onInserted(mMergedSize - itemCount, itemCount); 215 | break; 216 | } 217 | 218 | if (newDataStart == newDataSize) { 219 | // No more new items, copy the remaining old items. 220 | int itemCount = mOldDataSize - mOldDataStart; 221 | System.arraycopy(mOldData, mOldDataStart, mData, mMergedSize, itemCount); 222 | mMergedSize += itemCount; 223 | break; 224 | } 225 | 226 | T oldItem = mOldData[mOldDataStart]; 227 | T newItem = newData[newDataStart]; 228 | int compare = mCallback.compare(oldItem, newItem); 229 | if (compare > 0) { 230 | // New item is lower, output it. 231 | mData[mMergedSize++] = newItem; 232 | mSize++; 233 | newDataStart++; 234 | mCallback.onInserted(mMergedSize - 1, 1); 235 | } else if (compare == 0 && mCallback.areItemsTheSame(oldItem, newItem)) { 236 | // Items are the same. Output the new item, but consume both. 237 | mData[mMergedSize++] = newItem; 238 | newDataStart++; 239 | mOldDataStart++; 240 | if (!mCallback.areContentsTheSame(oldItem, newItem)) { 241 | mCallback.onChanged(mMergedSize - 1, 1); 242 | } 243 | } else { 244 | // Old item is lower than or equal to (but not the same as the new). Output it. 245 | // New item with the same sort order will be inserted later. 246 | mData[mMergedSize++] = oldItem; 247 | mOldDataStart++; 248 | } 249 | } 250 | } 251 | 252 | private void throwIfMerging() { 253 | if (mOldData != null) { 254 | throw new IllegalStateException("Cannot call this method from within addAll"); 255 | } 256 | } 257 | 258 | public void beginBatchedUpdates() { 259 | throwIfMerging(); 260 | if (mCallback instanceof RxSortedListCallback.BatchedCallback) { 261 | return; 262 | } 263 | if (mBatchedCallback == null) { 264 | mBatchedCallback = new RxSortedListCallback.BatchedCallback(mCallback); 265 | } 266 | mCallback = mBatchedCallback; 267 | } 268 | 269 | public void endBatchedUpdates() { 270 | throwIfMerging(); 271 | if (mCallback instanceof RxSortedListCallback.BatchedCallback) { 272 | ((RxSortedListCallback.BatchedCallback) mCallback).dispatchLastEvent(); 273 | } 274 | if (mCallback == mBatchedCallback) { 275 | mCallback = mBatchedCallback.mWrappedCallback; 276 | } 277 | } 278 | 279 | private int add(T item, boolean notify) { 280 | int index = findIndexOf(item, mData, 0, mSize, INSERTION); 281 | if (index == INVALID_POSITION) { 282 | index = 0; 283 | } else if (index < mSize) { 284 | T existing = mData[index]; 285 | if (mCallback.areItemsTheSame(existing, item)) { 286 | if (mCallback.areContentsTheSame(existing, item)) { 287 | //no change but still replace the item 288 | mData[index] = item; 289 | return index; 290 | } else { 291 | mData[index] = item; 292 | mCallback.onChanged(index, 1); 293 | return index; 294 | } 295 | } 296 | } 297 | addToData(index, item); 298 | if (notify) { 299 | mCallback.onInserted(index, 1); 300 | } 301 | return index; 302 | } 303 | 304 | public boolean remove(T item) { 305 | throwIfMerging(); 306 | return remove(item, true); 307 | } 308 | 309 | public T removeItemAt(int index) { 310 | throwIfMerging(); 311 | T item = get(index); 312 | removeItemAtIndex(index, true); 313 | return item; 314 | } 315 | 316 | private boolean remove(T item, boolean notify) { 317 | int index = findIndexOf(item, mData, 0, mSize, DELETION); 318 | if (index == INVALID_POSITION) { 319 | return false; 320 | } 321 | removeItemAtIndex(index, notify); 322 | return true; 323 | } 324 | 325 | private void removeItemAtIndex(int index, boolean notify) { 326 | System.arraycopy(mData, index + 1, mData, index, mSize - index - 1); 327 | mSize--; 328 | mData[mSize] = null; 329 | if (notify) { 330 | mCallback.onRemoved(index, 1); 331 | } 332 | } 333 | 334 | public void updateItemAt(int index, T item) { 335 | throwIfMerging(); 336 | final T existing = get(index); 337 | // assume changed if the same object is given back 338 | boolean contentsChanged = existing == item || !mCallback.areContentsTheSame(existing, item); 339 | if (existing != item) { 340 | // different items, we can use comparison and may avoid lookup 341 | final int cmp = mCallback.compare(existing, item); 342 | if (cmp == 0) { 343 | mData[index] = item; 344 | if (contentsChanged) { 345 | mCallback.onChanged(index, 1); 346 | } 347 | return; 348 | } 349 | } 350 | if (contentsChanged) { 351 | mCallback.onChanged(index, 1); 352 | } 353 | // TODO this done in 1 pass to avoid shifting twice. 354 | removeItemAtIndex(index, false); 355 | int newIndex = add(item, false); 356 | if (index != newIndex) { 357 | mCallback.onMoved(index, newIndex); 358 | } 359 | } 360 | 361 | public void recalculatePositionOfItemAt(int index) { 362 | throwIfMerging(); 363 | // TODO can be improved 364 | final T item = get(index); 365 | removeItemAtIndex(index, false); 366 | int newIndex = add(item, false); 367 | if (index != newIndex) { 368 | mCallback.onMoved(index, newIndex); 369 | } 370 | } 371 | 372 | public T get(int index) throws IndexOutOfBoundsException { 373 | if (index >= mSize || index < 0) { 374 | throw new IndexOutOfBoundsException("Asked to get item at " + index + " but size is " 375 | + mSize); 376 | } 377 | if (mOldData != null) { 378 | // The call is made from a callback during addAll execution. The data is split 379 | // between mData and mOldData. 380 | if (index >= mMergedSize) { 381 | return mOldData[index - mMergedSize + mOldDataStart]; 382 | } 383 | } 384 | return mData[index]; 385 | } 386 | 387 | public int indexOf(T item) { 388 | if (mOldData != null) { 389 | int index = findIndexOf(item, mData, 0, mMergedSize, LOOKUP); 390 | if (index != INVALID_POSITION) { 391 | return index; 392 | } 393 | index = findIndexOf(item, mOldData, mOldDataStart, mOldDataSize, LOOKUP); 394 | if (index != INVALID_POSITION) { 395 | return index - mOldDataStart + mMergedSize; 396 | } 397 | return INVALID_POSITION; 398 | } 399 | return findIndexOf(item, mData, 0, mSize, LOOKUP); 400 | } 401 | 402 | private int findIndexOf(T item, T[] mData, int left, int right, int reason) { 403 | while (left < right) { 404 | final int middle = (left + right) / 2; 405 | T myItem = mData[middle]; 406 | final int cmp = mCallback.compare(myItem, item); 407 | if (cmp < 0) { 408 | left = middle + 1; 409 | } else if (cmp == 0) { 410 | if (mCallback.areItemsTheSame(myItem, item)) { 411 | return middle; 412 | } else { 413 | int exact = linearEqualitySearch(item, middle, left, right); 414 | if (reason == INSERTION) { 415 | return exact == INVALID_POSITION ? middle : exact; 416 | } else { 417 | return exact; 418 | } 419 | } 420 | } else { 421 | right = middle; 422 | } 423 | } 424 | return reason == INSERTION ? left : INVALID_POSITION; 425 | } 426 | 427 | private int linearEqualitySearch(T item, int middle, int left, int right) { 428 | // go left 429 | for (int next = middle - 1; next >= left; next--) { 430 | T nextItem = mData[next]; 431 | int cmp = mCallback.compare(nextItem, item); 432 | if (cmp != 0) { 433 | break; 434 | } 435 | if (mCallback.areItemsTheSame(nextItem, item)) { 436 | return next; 437 | } 438 | } 439 | for (int next = middle + 1; next < right; next++) { 440 | T nextItem = mData[next]; 441 | int cmp = mCallback.compare(nextItem, item); 442 | if (cmp != 0) { 443 | break; 444 | } 445 | if (mCallback.areItemsTheSame(nextItem, item)) { 446 | return next; 447 | } 448 | } 449 | return INVALID_POSITION; 450 | } 451 | 452 | private void addToData(int index, T item) { 453 | if (index > mSize) { 454 | throw new IndexOutOfBoundsException( 455 | "cannot add item to " + index + " because size is " + mSize); 456 | } 457 | if (mSize == mData.length) { 458 | // we are at the limit enlarge 459 | T[] newData = (T[]) Array.newInstance(mTClass, mData.length + CAPACITY_GROWTH); 460 | System.arraycopy(mData, 0, newData, 0, index); 461 | newData[index] = item; 462 | System.arraycopy(mData, index, newData, index + 1, mSize - index); 463 | mData = newData; 464 | } else { 465 | // just shift, we fit 466 | System.arraycopy(mData, index, mData, index + 1, mSize - index); 467 | mData[index] = item; 468 | } 469 | mSize++; 470 | } 471 | 472 | /** 473 | * Removes all items from the SortedList. 474 | */ 475 | public void clear() { 476 | throwIfMerging(); 477 | if (mSize == 0) { 478 | return; 479 | } 480 | final int prevSize = mSize; 481 | Arrays.fill(mData, 0, prevSize, null); 482 | mSize = 0; 483 | mCallback.onRemoved(0, prevSize); 484 | } 485 | 486 | } --------------------------------------------------------------------------------