├── .gitignore ├── .idea └── codeStyleSettings.xml ├── .travis.yml ├── BENCHMARK.md ├── LICENSE ├── README.md ├── build.gradle ├── droidsnapper-sample-rx ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── example │ │ └── snapper │ │ └── rx │ │ ├── App.java │ │ ├── MainActivity.java │ │ ├── SnapperRxListAdapter.java │ │ └── util │ │ ├── RxSnapperListener.java │ │ ├── SnapperChangeFilter.java │ │ ├── SnapperChangeMapper.java │ │ └── SnapperChangeSort.java │ ├── project.properties │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── droidsnapper-sample ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── example │ │ └── snapper │ │ ├── App.java │ │ ├── MainActivity.java │ │ └── ProjectionArrayAdapter.java │ ├── project.properties │ └── res │ ├── layout │ ├── activity_main.xml │ └── user_cell.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── droidsnapper ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── io │ │ └── techery │ │ └── snapper │ │ ├── BaseAsyncTestCase.java │ │ ├── BaseSyncTestCase.java │ │ ├── BaseTestCase.java │ │ ├── model │ │ ├── Company.java │ │ └── User.java │ │ ├── test │ │ ├── BasicOperationsTest.java │ │ ├── HelpersTest.java │ │ ├── ManyCollectionsTest.java │ │ └── benchmark │ │ │ ├── PerformanceTest.java │ │ │ └── ProjectionPerformanceTest.java │ │ └── util │ │ └── ModelUtil.java │ └── main │ ├── AndroidManifest.xml │ └── java │ └── io │ └── techery │ └── snapper │ └── droidsnapper │ ├── DroidSnapper.java │ └── helper │ └── MainThreadDataListener.java ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle ├── snapper-converters └── kryo │ ├── build.gradle │ └── src │ └── main │ └── java │ └── io │ └── techery │ └── snapper │ └── kryo │ ├── KryoConverter.java │ └── KryoConverterFactory.java ├── snapper-persisters └── snappydb │ ├── build.gradle │ └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── io │ └── techery │ └── snapper │ └── snappydb │ ├── SnappyStorageFactory.java │ ├── SnappyStoragePersister.java │ ├── SnappyStoragePersisterFactory.java │ └── SnappySweeper.java └── snapper ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src └── main └── java └── io └── techery └── snapper ├── Snapper.java ├── converter ├── ObjectConverter.java └── ObjectConverterFactory.java ├── datacollection ├── DataCollection.java ├── DataCollectionFactory.java ├── DefaultDataCollectionFactory.java └── naming │ ├── DataCollectionNamingFactory.java │ └── DefaultDataCollectionNamingFactory.java ├── dataset ├── DataSet.java ├── DataSetJoin.java ├── DataSetMap.java └── IDataSet.java ├── executor ├── ExecutorFactory.java ├── FixedExecutorFactory.java ├── SimpleExecutorService.java └── SnapperThreadFactory.java ├── helper └── SingleItemDataListener.java ├── model ├── Indexable.java └── ItemRef.java ├── projection ├── IProjection.java ├── Projection.java └── ProjectionBuilder.java ├── storage ├── CachingStorage.java ├── Storage.java ├── StorageChange.java ├── StorageFactory.java ├── StoragePersister.java └── StoragePersisterFactory.java ├── sweeper └── Sweeper.java └── util └── ListUtils.java /.gitignore: -------------------------------------------------------------------------------- 1 | # svn 2 | *.svn* 3 | 4 | # built application files 5 | *.apk 6 | *.ap_ 7 | 8 | # files for the dex VM 9 | *.dex 10 | 11 | # Java class files 12 | *.class 13 | 14 | # generated GUI files 15 | */R.java 16 | 17 | # generated folder 18 | bin 19 | gen 20 | 21 | # local 22 | local.properties 23 | proguard.cfg 24 | 25 | # log files 26 | log*.txt 27 | 28 | # archives 29 | *.gz 30 | *.tar 31 | *.zip 32 | 33 | # eclipse 34 | *.metadata 35 | *.settings 36 | 37 | # Android Studio 38 | .idea/* 39 | **/*/.idea 40 | !.idea/codeStyleSettings.xml 41 | .gradle 42 | */local.properties 43 | */out 44 | build 45 | *.iml 46 | *.iws 47 | *.ipr 48 | *~ 49 | *.swp 50 | 51 | .DS_Store -------------------------------------------------------------------------------- /.idea/codeStyleSettings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 227 | 229 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | jdk: oraclejdk8 3 | 4 | ### Dependencies 5 | 6 | env: 7 | global: 8 | - ANDROID_TARGET=android-23 9 | - ANDROID_EMULATOR_TARGET=android-21 10 | - ANDROID_ABI=armeabi-v7a 11 | - ANDROID_BUILD_TOOLS=23.0.3 12 | - ADB_INSTALL_TIMEOUT=8 # avoid timeout exception 13 | 14 | android: 15 | components: 16 | - tools 17 | - platform-tools 18 | - build-tools-$ANDROID_BUILD_TOOLS 19 | - $ANDROID_TARGET 20 | - ANDROID_EMULATOR_TARGET 21 | - sys-img-$ANDROID_ABI-$ANDROID_EMULATOR_TARGET 22 | - extra-android-support 23 | - extra-android-m2repository 24 | licenses: 25 | - 'android-sdk-license-.+' 26 | 27 | ### Misc. configurations 28 | 29 | sudo: false 30 | before_cache: 31 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 32 | cache: 33 | directories: 34 | - $HOME/.m2 35 | - $HOME/.gradle/caches/ 36 | - $HOME/.gradle/wrapper/ 37 | 38 | ### Emulator preparations 39 | 40 | before_script: 41 | - echo no | android create avd --force -n test -t $ANDROID_EMULATOR_TARGET --abi $ANDROID_ABI 42 | - emulator -avd test -no-skin -no-audio -no-window -memory 256 & 43 | - android-wait-for-emulator 44 | - adb shell input keyevent 82 & 45 | 46 | ### The Job 47 | 48 | script: 49 | - ./gradlew --info clean droidsnapper:connectedAndroidTest droidsnapper:assembleDebug droidsnapper-sample:assembleDebug droidsnapper-sample-rx:assembleDebug -PdisablePreDex -------------------------------------------------------------------------------- /BENCHMARK.md: -------------------------------------------------------------------------------- 1 | ## Benchmark 2 | Insert/Load/Clear 25000 items on Emulator, Genymotion and Nexus 7 (2013). 3 | Benchmark tests are located at `io.techery.snapper.test.benchmark` package. 4 | 5 | ### Emulator 6 | 7 | + Insert 8 | ``` 9 | | 0.000 ms | Batch Insert 10 | | 3216.919 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 11 | | 57.606 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 12 | | 46.974 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 13 | | 65.759 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 14 | | 59.351 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 15 | | 38.515 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 16 | | 2.051 ms | END of Batch Insert 17 | | 18 | final: 3487.175 ms 19 | ``` 20 | 21 | + Load 22 | ``` 23 | | 0.000 ms | Batch Load 24 | | 2396.487 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 25 | | 42.216 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 26 | | 23.289 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 27 | | 37.384 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 28 | | 51.291 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 29 | | 50.593 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 30 | | 2.112 ms | END of Batch Load 31 | | 32 | final: 2603.371 ms 33 | ``` 34 | 35 | + Clear 36 | ``` 37 | | 0.000 ms | Batch Clear 38 | | 926.022 ms | Storage update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 39 | | 4601.738 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 40 | | 3726.414 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 41 | | 3499.932 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 42 | | 3464.880 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 43 | | 3698.451 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 44 | | 1.578 ms | END of Batch Clear 45 | | 46 | final: 19919.015 ms 47 | ``` 48 | 49 | ### Genymotion 50 | 51 | + Insert 52 | ``` 53 | | 0.000 ms | Batch Insert 54 | | 2707.703 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 55 | | 217.081 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 56 | | 123.055 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 57 | | 116.949 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 58 | | 107.740 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 59 | | 150.817 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 60 | | 0.035 ms | END of Batch Insert 61 | | 62 | final: 3423.381 ms 63 | ``` 64 | 65 | + Load 66 | ``` 67 | | 0.000 ms | Batch Load 68 | | 2287.892 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 69 | | 126.722 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 70 | | 147.331 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 71 | | 144.558 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 72 | | 118.805 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 73 | | 143.937 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 74 | | 0.033 ms | END of Batch Load 75 | | 76 | final: 2969.278 ms 77 | ``` 78 | 79 | + Clear 80 | ``` 81 | | 0.000 ms | Batch Clear 82 | | 771.553 ms | Storage update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 83 | | 22550.293 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 84 | | 22153.366 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 85 | | 21780.841 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 86 | | 20937.838 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 87 | | 20756.431 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 88 | | 0.034 ms | END of Batch Clear 89 | | 90 | final: 108950.357 ms 91 | ``` 92 | 93 | ### Nexus 7 (2013) 94 | 95 | + Insert 96 | ``` 97 | | 0.000 ms | Batch Insert 98 | | 7083.557 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 99 | | 354.095 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 100 | | 272.369 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 101 | | 361.389 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 102 | | 179.077 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 103 | | 292.511 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 104 | | 0.092 ms | END of Batch Insert 105 | | 106 | final: 8543.091 ms 107 | ``` 108 | 109 | + Load 110 | ``` 111 | | 0.000 ms | Batch Load 112 | | 7984.528 ms | Storage update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 113 | | 337.952 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 114 | | 296.509 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 115 | | 309.448 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 116 | | 320.160 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 117 | | 328.094 ms | Projection update, items count is 25000 change is StorageChange{added=25000, updated=0, removed=0} 118 | | 0.305 ms | END of Batch Load 119 | | 120 | final: 9576.996 ms 121 | ``` 122 | 123 | + Clear 124 | ``` 125 | | 0.000 ms | Batch Clear 126 | | 2934.570 ms | Storage update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 127 | | 38443.512 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 128 | | 38543.610 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 129 | | 37971.191 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 130 | | 38011.871 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 131 | | 38447.601 ms | Projection update, items count is 0 change is StorageChange{added=0, updated=0, removed=25000} 132 | | 0.092 ms | END of Batch Clear 133 | | 134 | final: 194352.448 ms 135 | ``` 136 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 {yyyy} {name of copyright owner} 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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Snapper 2 | NoSQL fast-serializable storage with Projections, Sorting, Filtering and more. 3 | 4 | ## Overview 5 | NoSQL db is great in simplicity. 6 | `Snapper` is simple but yet functional: 7 | it's based on idea that every `POJO` could be addressed as typed `DataCollection` with 8 | any kind of `Projection` (aka sub-set) for filtering, sorting, mapping or joining. 9 | Such `DataCollection`\\`Projection` is observable and reacts to changes from parent `DataSet`. 10 | 11 | ## Performance 12 | Timing is very close to fastest `SQLite`-based DBs. 13 | See [Benchmark test results](BENCHMARK.md) for details. 14 | 15 | ## Getting started 16 | ### Core objects 17 | `DroidSnapper` is main controller for `DataCollection`(s) - data provider objects. 18 | It's thread safe Singleton: 19 | 20 | ```java 21 | DataCollection userCollection = DroidSnapper.with(context).collection(User.class); 22 | ``` 23 | `DataCollection` itself is used for: 24 | - data manipulation 25 | 26 | ```java 27 | userCollection.insert(new User(1, "Jim")); // add user with id=1 28 | userCollection.insert(new User(1, "Jim Defoe")); // replace user by id 29 | ``` 30 | _Note_: all data-related work is done on background `Executor` so `MainThread`-friendly. 31 | - data observation 32 | 33 | ```java 34 | userCollection.addDataListener(new IDataSet.DataListener() { 35 | @Override 36 | public void onDataUpdated(List items, StorageChange change) { 37 | // 38 | } 39 | }); 40 | ``` 41 | _Note_: `DataCollection` holds memory cache from it's storage for better performance; 42 | 43 | _Note_: listener is called right away upon addition. It's guaranteed that `DataCollection` is in costistent state (read initialized) when callback is called. 44 | 45 | _Caution_: listener is called from `Executor`'s thread, 46 | it's up to `DataListener` to proxy calls to another thread, e.g. [MainThreadDataListener](droidsnapper/src/main/java/io/techery/snapper/droidsnapper/helper/MainThreadDataListener.java). 47 | - `Projection` creation: 48 | 49 | ```java 50 | Projection jimProjection = userCollection.projection() 51 | .where(new Predicate() { 52 | @Override 53 | public boolean apply(User element) { 54 | return element.name.contains("Jim"); 55 | } 56 | }).build(); 57 | jimProjection.addDataListener(...); 58 | ``` 59 | `Projection` is a subset of parent `DataSet` which `DataCollection` or another `Projection` is. 60 | It's used for: 61 | - sub-projection with conditional filtering/sorting; 62 | - data observation. 63 | 64 | ### Data Model 65 | Every model must implement `Indexable` interface, e.g.: 66 | ```java 67 | public class User implements Indexable { 68 | 69 | public final int id; 70 | 71 | public User(int id) { 72 | this.id = id; 73 | } 74 | 75 | @Override 76 | public byte[] index() { 77 | return ByteBuffer.allocate(4).putInt(id).array(); 78 | } 79 | } 80 | ``` 81 | - `index()` is used as unique key for each object; 82 | - insertion will replace (update) object with same index. 83 | 84 | ## Advanced usage 85 | ### DataCollection naming 86 | Every POJO storage is named with POJO's `class#getSimpleName()`, but could be labeled for uniqueness: 87 | ```java 88 | DataCollection userCollection = DroidSnapper.with(context).collection(User.class); 89 | DataCollection friendsCollection = DroidSnapper.with(context).collection(User.class, "friends"); 90 | ``` 91 | ### Advanced DataSet(s) 92 | #### Joining 93 | Connects two `DataSet`s to listen for their changes: 94 | ```java 95 | DataSetJoin> companyUserJoin = 96 | new JoinBuilder<>(companyStorage, userStorage) 97 | .setJoinFunction(new Function2() { 98 | @Override public Boolean apply(Company company, User user) { 99 | return company.getId() == user.getCompanyId(); 100 | } 101 | }) 102 | .setMapFunction(new Function2, Pair>() { 103 | @Override public Pair apply(Company company, List users) { 104 | User user = users.isEmpty() ? null : users.get(0); 105 | return new Pair<>(company, user); 106 | } 107 | }).create(); 108 | ``` 109 | #### Mapping 110 | Creates virtual relation between `DataSet` objects and some type: 111 | ```java 112 | DataSetMap userIdMap = new DataSetMap(dataCollection, new Function1() { 113 | @Override 114 | public Integer apply(User user) { 115 | return user.id; 116 | } 117 | }); 118 | userIdMap.addDataListener(new IDataSet.DataListener() { 119 | @Override 120 | public void onDataUpdated(List items, StorageChange change) { 121 | // 122 | } 123 | }); 124 | ``` 125 | #### Rx support 126 | `DataListener` is wrappable with Rx goodies, see [Rx Sample](droidsnapper-sample-rx/src/main/java/com/example/snapper/rx) for details. 127 | 128 | ### Resources Cleanup 129 | - Every collection could be closed with `DataCollection#close()` 130 | - All collections are closed via `Snapper#close()` 131 | 132 | ## Under the hood 133 | `DroidSnapper` is a `Snapper` instance with default impl. of `Snapper`'s components, those are: 134 | - `DataCollectionNamingFactory` - creates names for collections depending on it's model's class and custom label; 135 | - `DataCollectionFactory` creates a `DataCollection` per POJO's model, every collection involves; 136 | - `StorageFactory` provides storage to put/get collection's items; 137 | - `ExecutorFactory` provides `ExecutorService` to perform collection actions; 138 | 139 | `Storage` impl. could differ and up to developer. 140 | Anyway `Snapper` provides `CachingStorage` with in-mem cache and forwarding calls to it's disk persister. 141 | `CachingStorage` uses `ObjectConverter` to convert POJO to bytes and vice versa. 142 | 143 | It means one can easily create own no-sql storage with own components of choice. 144 | 145 | `DroidSnapper` uses 146 | - `CachingStorage` to hold collection's items in memory for best performance; 147 | - [SnappyDB](https://github.com/nhachicha/SnappyDB) as `StoragePersister` 148 | - [Kryo](https://github.com/EsotericSoftware/kryo) as `ObjectConverter` 149 | 150 | ## Dev. status 151 | Tested in production. 152 | 153 | [![Build Status](https://travis-ci.org/techery/snapper.svg?branch=master)](https://travis-ci.org/techery/snapper) 154 | ![JitPack release](https://img.shields.io/github/tag/techery/snapper.svg?label=JitPack) 155 | 156 | ## Installation 157 | ```groovy 158 | repositories { 159 | maven { url "https://jitpack.io" } 160 | } 161 | dependencies { 162 | compile 'com.github.techery.snapper:droidsnapper:{latestVersion}' 163 | } 164 | ``` 165 | 166 | ## License 167 | 168 | Copyright (c) 2015 Techery 169 | 170 | Licensed under the Apache License, Version 2.0 (the "License"); 171 | you may not use this file except in compliance with the License. 172 | You may obtain a copy of the License at 173 | 174 | http://www.apache.org/licenses/LICENSE-2.0 175 | 176 | Unless required by applicable law or agreed to in writing, software 177 | distributed under the License is distributed on an "AS IS" BASIS, 178 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 179 | See the License for the specific language governing permissions and 180 | limitations under the License. 181 | 182 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | repositories { 4 | jcenter() 5 | } 6 | dependencies { 7 | classpath 'com.android.tools.build:gradle:2.0.0' 8 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' 9 | classpath 'com.github.ben-manes:gradle-versions-plugin:0.12.0' 10 | } 11 | } 12 | 13 | ext { 14 | compileSdkVersion = 23 15 | buildToolsVersion = '23.0.3' 16 | minSdkVersion = 15 17 | targetSdkVersion = 22 18 | } 19 | 20 | /////////////////////////////////// 21 | // Misc dependencies and properties 22 | /////////////////////////////////// 23 | 24 | // System properties 25 | ext.preDexLibs = !project.hasProperty('disablePreDex') -------------------------------------------------------------------------------- /droidsnapper-sample-rx/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | } 5 | dependencies { 6 | classpath 'com.android.tools.build:gradle:2.0.0' 7 | classpath 'me.tatarka:gradle-retrolambda:3.2.5' 8 | classpath 'com.github.ben-manes:gradle-versions-plugin:0.12.0' 9 | } 10 | } 11 | 12 | apply plugin: 'com.android.application' 13 | apply plugin: 'me.tatarka.retrolambda' 14 | apply plugin: 'com.github.ben-manes.versions' 15 | 16 | android { 17 | compileSdkVersion rootProject.ext.compileSdkVersion 18 | buildToolsVersion rootProject.ext.buildToolsVersion 19 | 20 | defaultConfig { 21 | applicationId "com.example.droidsnapper.rx" 22 | minSdkVersion rootProject.ext.minSdkVersion 23 | targetSdkVersion rootProject.ext.targetSdkVersion 24 | } 25 | 26 | buildTypes { 27 | release { 28 | minifyEnabled false 29 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 30 | } 31 | } 32 | 33 | compileOptions { 34 | sourceCompatibility JavaVersion.VERSION_1_8 35 | targetCompatibility JavaVersion.VERSION_1_8 36 | } 37 | } 38 | 39 | repositories { 40 | jcenter() 41 | maven { url "https://jitpack.io" } 42 | } 43 | 44 | dependencies { 45 | compile project(':droidsnapper') 46 | // 47 | compile 'io.reactivex:rxjava:1.1.3' 48 | compile 'io.reactivex:rxandroid:1.1.0' 49 | compile 'com.trello:rxlifecycle:0.5.0' 50 | compile 'com.trello:rxlifecycle-components:0.5.0' 51 | compile 'com.jakewharton.rxbinding:rxbinding:0.4.0' 52 | // 53 | compile 'com.github.techery:RxListAdapter:0.1.1' 54 | // 55 | compile 'com.android.support:appcompat-v7:23.3.0' 56 | // 57 | compile 'com.jakewharton:butterknife:7.0.1' 58 | compile 'com.jakewharton.timber:timber:4.1.2' 59 | } 60 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/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/zen/Library/Android/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 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 13 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/App.java: -------------------------------------------------------------------------------- 1 | package com.example.snapper.rx; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | import timber.log.Timber; 7 | import timber.log.Timber.DebugTree; 8 | 9 | public class App extends Application { 10 | 11 | @Override 12 | public void onCreate() { 13 | super.onCreate(); 14 | instance = this; 15 | 16 | if (BuildConfig.DEBUG) { 17 | Timber.plant(new DebugTree()); 18 | } else { 19 | // TODO Crashlytics.start(this); 20 | // TODO Timber.plant(new CrashlyticsTree()); 21 | } 22 | 23 | } 24 | 25 | /////////////////////////////////////////////////////////////////////////// 26 | // Static helper 27 | /////////////////////////////////////////////////////////////////////////// 28 | 29 | public static App from(Context context) { 30 | return (App) context.getApplicationContext(); 31 | } 32 | 33 | private static App instance; 34 | 35 | public static App instance() { 36 | return instance; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.snapper.rx; 2 | 3 | import android.content.Context; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.support.v7.widget.LinearLayoutManager; 7 | import android.support.v7.widget.RecyclerView; 8 | import android.util.Pair; 9 | import android.view.LayoutInflater; 10 | import android.view.View; 11 | import android.view.ViewGroup; 12 | import android.widget.TextView; 13 | 14 | import com.example.snapper.rx.util.RxSnapperListener; 15 | import com.example.snapper.rx.util.SnapperChangeFilter; 16 | import com.example.snapper.rx.util.SnapperChangeSort; 17 | 18 | import java.nio.ByteBuffer; 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | 22 | import butterknife.Bind; 23 | import butterknife.ButterKnife; 24 | import butterknife.OnClick; 25 | import io.techery.snapper.datacollection.DataCollection; 26 | import io.techery.snapper.droidsnapper.DroidSnapper; 27 | import io.techery.snapper.model.Indexable; 28 | import io.techery.snapper.projection.IProjection; 29 | import io.techery.snapper.storage.StorageChange; 30 | import rx.Observable; 31 | import rx.subjects.ReplaySubject; 32 | 33 | 34 | public class MainActivity extends AppCompatActivity { 35 | 36 | DataCollection dataCollection; 37 | IProjection projection; 38 | // 39 | ReplaySubject filteringSignal = ReplaySubject.createWithSize(1); 40 | volatile int lastId; 41 | // 42 | static final int BATCH_PUT_COUNT = 10000; 43 | 44 | @Bind(R.id.listView) 45 | RecyclerView recyclerView; 46 | UserAdapter usersAdapter; 47 | 48 | @Override 49 | protected void onCreate(Bundle savedInstanceState) { 50 | super.onCreate(savedInstanceState); 51 | setContentView(R.layout.activity_main); 52 | ButterKnife.bind(this); 53 | 54 | dataCollection = DroidSnapper.with(this).collection(User.class); 55 | projection = dataCollection.projection().build(); 56 | // 57 | RxSnapperListener snapperListener = new RxSnapperListener<>(); 58 | projection.addDataListener(snapperListener); 59 | 60 | boolean filter; 61 | if (savedInstanceState == null) filter = false; 62 | else filter = savedInstanceState.getBoolean("filter"); 63 | filteringSignal.onNext(filter); 64 | 65 | Observable, StorageChange>> source = 66 | filteringSignal.asObservable() 67 | .flatMap(filterOn -> snapperListener.observable() 68 | .compose(new SnapperChangeSort<>((u1, u2) -> { 69 | if (u1.id < u2.id) return 1; 70 | else if (u1.id > u2.id) return -1; 71 | else return 0; 72 | })) 73 | .doOnNext(pair -> { 74 | List items = pair.first; 75 | if (items.isEmpty()) lastId = 0; 76 | else lastId = items.get(0).id; 77 | }) 78 | .compose(new SnapperChangeFilter<>(user -> { 79 | if (!filterOn) return true; 80 | else return user.id % 10 == 0; 81 | })) 82 | ); 83 | usersAdapter = new UserAdapter(this, source); 84 | recyclerView.setAdapter(usersAdapter); 85 | recyclerView.setLayoutManager(new LinearLayoutManager(this)); 86 | } 87 | 88 | @Override 89 | public void onSaveInstanceState(Bundle outState) { 90 | super.onSaveInstanceState(outState); 91 | outState.putBoolean("filter", filteringSignal.getValue()); 92 | } 93 | 94 | @Override 95 | protected void onDestroy() { 96 | projection.close(); 97 | super.onDestroy(); 98 | } 99 | 100 | @OnClick(R.id.add) 101 | void onAddClick() { 102 | dataCollection.insert(genUser(lastId + 1)); 103 | } 104 | 105 | @OnClick(R.id.add_many) 106 | void onAddManyClick() { 107 | List users = new ArrayList<>(); 108 | int lastId = this.lastId + 1; 109 | for (int i = 0; i < BATCH_PUT_COUNT; i++) { 110 | users.add(genUser(lastId + i)); 111 | } 112 | dataCollection.insertAll(users); 113 | } 114 | 115 | @OnClick(R.id.filter) 116 | void onFilterClick() { 117 | filteringSignal.onNext(!filteringSignal.getValue()); 118 | } 119 | 120 | @OnClick(R.id.clear) 121 | void onClearClick() { 122 | dataCollection.clear(); 123 | } 124 | 125 | /////////////////////////////////////////////////////////////////////////// 126 | // Adapter 127 | /////////////////////////////////////////////////////////////////////////// 128 | 129 | static class UserAdapter extends SnapperRxListAdapter { 130 | 131 | public UserAdapter(Context context, Observable, StorageChange>> source) { 132 | super(context, source); 133 | } 134 | 135 | @Override 136 | public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 137 | LayoutInflater inflater = LayoutInflater.from(context); 138 | View itemView = inflater.inflate(android.R.layout.simple_list_item_1, parent, false); 139 | return new ViewHolder(itemView); 140 | } 141 | 142 | @Override 143 | public void onBindViewHolder(ViewHolder holder, int position) { 144 | User user = getItem(position); 145 | ((TextView) holder.itemView).setText(String.valueOf(user.getId())); 146 | } 147 | 148 | static class ViewHolder extends RecyclerView.ViewHolder { 149 | 150 | public ViewHolder(View itemView) { 151 | super(itemView); 152 | } 153 | } 154 | } 155 | 156 | 157 | /////////////////////////////////////////////////////////////////////////// 158 | // User model 159 | /////////////////////////////////////////////////////////////////////////// 160 | 161 | static User genUser(int i) { 162 | User u = new User(i); 163 | u.email = String.valueOf(Math.random() * 100); 164 | u.name = String.valueOf(Math.random() * 100); 165 | u.price = (float) Math.random(); 166 | u.isActive = Math.random() % 2 == 0; 167 | return u; 168 | } 169 | 170 | public static class User implements Indexable { 171 | public int id; 172 | public String name; 173 | public float price; 174 | public String email; 175 | 176 | public boolean isActive; 177 | 178 | public User() { 179 | } 180 | 181 | public User(int id) { 182 | this.id = id; 183 | } 184 | 185 | @Override 186 | public byte[] index() { 187 | return ByteBuffer.allocate(4).putInt(id).array(); 188 | } 189 | 190 | @Override 191 | public boolean equals(Object o) { 192 | if (this == o) return true; 193 | if (o == null || getClass() != o.getClass()) return false; 194 | 195 | User user = (User) o; 196 | 197 | return id == user.id; 198 | 199 | } 200 | 201 | @Override 202 | public int hashCode() { 203 | return id; 204 | } 205 | 206 | public int getId() { 207 | return id; 208 | } 209 | 210 | public void setId(int id) { 211 | this.id = id; 212 | } 213 | 214 | public String getName() { 215 | return name; 216 | } 217 | 218 | public void setName(String name) { 219 | this.name = name; 220 | } 221 | 222 | public float getPrice() { 223 | return price; 224 | } 225 | 226 | public void setPrice(float price) { 227 | this.price = price; 228 | } 229 | 230 | public String getEmail() { 231 | return email; 232 | } 233 | 234 | public void setEmail(String email) { 235 | this.email = email; 236 | } 237 | 238 | public boolean isActive() { 239 | return isActive; 240 | } 241 | 242 | public void setIsActive(boolean isActive) { 243 | this.isActive = isActive; 244 | } 245 | 246 | @Override 247 | public String toString() { 248 | return "User{" + 249 | "id=" + id + 250 | '}'; 251 | } 252 | 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/SnapperRxListAdapter.java: -------------------------------------------------------------------------------- 1 | package com.example.snapper.rx; 2 | 3 | import android.content.Context; 4 | import android.support.v7.widget.RecyclerView; 5 | import android.util.Pair; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import io.techery.rxlistadapter.RxAdapterBridge; 11 | import io.techery.rxlistadapter.RxListAdapter; 12 | import io.techery.snapper.model.ItemRef; 13 | import io.techery.snapper.storage.StorageChange; 14 | import rx.Observable; 15 | import rx.Subscriber; 16 | 17 | public abstract class SnapperRxListAdapter extends RxListAdapter, StorageChange>, VH> { 18 | 19 | public SnapperRxListAdapter(Context context, Observable, StorageChange>> source) { 20 | super(context, new ArrayList<>(), source); 21 | } 22 | 23 | @Override 24 | public RxAdapterBridge, StorageChange>> createRxAdapterBridge(List items, Observable, StorageChange>> source) { 25 | return new RxChangeAdapterBridge(this, source, items); 26 | } 27 | 28 | private static class RxChangeAdapterBridge extends RxAdapterBridge, StorageChange>> { 29 | 30 | public RxChangeAdapterBridge(RecyclerView.Adapter adapter, Observable, StorageChange>> source, List items) { 31 | super(adapter, source, items); 32 | } 33 | 34 | @Override protected Subscriber, StorageChange>> subscriber() { 35 | return new Subscriber, StorageChange>>() { 36 | @Override public void onNext(Pair, StorageChange> ts) { 37 | List newItems = ts.first; 38 | StorageChange storageChange = ts.second; 39 | if (itemsEquals(newItems, storageChange)) return; 40 | // 41 | if (items.isEmpty()) { 42 | setNewItems(newItems); 43 | } else { 44 | for (ItemRef item : storageChange.getAdded()) { 45 | onAdded(newItems, item.getValue()); 46 | } 47 | for (ItemRef item : storageChange.getRemoved()) { 48 | onRemoved(item.getValue()); 49 | } 50 | for (ItemRef item : storageChange.getUpdated()) { 51 | onUpdated(newItems, item.getValue()); 52 | } 53 | } 54 | if (items.size() != newItems.size()) setNewItems(newItems); 55 | } 56 | 57 | private boolean itemsEquals(List newItems, StorageChange storageChange) { 58 | return items.equals(newItems) && storageChange.getUpdated().size() == 0; 59 | } 60 | 61 | private void setNewItems(List newItems) { 62 | items.clear(); 63 | items.addAll(newItems); 64 | adapter.notifyDataSetChanged(); 65 | } 66 | 67 | private void onAdded(List newItems, T value) { 68 | if (items.contains(value)) return; 69 | int i = newItems.indexOf(value); 70 | items.add(i, value); 71 | adapter.notifyItemInserted(i); 72 | } 73 | 74 | private void onRemoved(T item) { 75 | int pos = items.indexOf(item); 76 | if (pos == -1) return; 77 | items.remove(item); 78 | adapter.notifyItemRemoved(pos); 79 | } 80 | 81 | private void onUpdated(List newItems, T item) { 82 | int oldPos = items.indexOf(item); 83 | if (oldPos == -1) return; 84 | int newPos = newItems.indexOf(item); 85 | if (oldPos == newPos) { 86 | items.set(oldPos, item); 87 | adapter.notifyItemChanged(oldPos); 88 | } else { 89 | items.remove(oldPos); 90 | if (newPos > items.size()) newPos = items.size(); 91 | items.add(newPos, item); 92 | adapter.notifyItemMoved(oldPos, newPos); 93 | } 94 | } 95 | 96 | @Override public void onCompleted() { 97 | } 98 | 99 | @Override public void onError(Throwable e) { 100 | } 101 | }; 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/util/RxSnapperListener.java: -------------------------------------------------------------------------------- 1 | package com.example.snapper.rx.util; 2 | 3 | import android.util.Pair; 4 | 5 | import java.util.List; 6 | 7 | import io.techery.snapper.dataset.IDataSet; 8 | import io.techery.snapper.storage.StorageChange; 9 | import rx.Observable; 10 | import rx.functions.Func1; 11 | import rx.subjects.ReplaySubject; 12 | 13 | public class RxSnapperListener implements IDataSet.DataListener, IDataSet.StatusListener { 14 | 15 | private final ReplaySubject, StorageChange>> subject; 16 | private final String tag; 17 | 18 | public RxSnapperListener() { 19 | this(null); 20 | } 21 | 22 | public RxSnapperListener(String tag) { 23 | this.subject = ReplaySubject.createWithSize(1); 24 | this.tag = tag; 25 | } 26 | 27 | @Override public void onDataUpdated(List list, StorageChange storageChange) { 28 | subject.onNext(new Pair<>(list, storageChange)); 29 | } 30 | 31 | @Override public void onClosed() { 32 | subject.onCompleted(); 33 | } 34 | 35 | /////////////////////////////////////////////////////////////////////////// 36 | // Public 37 | /////////////////////////////////////////////////////////////////////////// 38 | 39 | public Observable, StorageChange>> observable() { 40 | return subject.asObservable(); 41 | } 42 | 43 | public Observable> listObservable() { 44 | return subject.map(new Func1, StorageChange>, List>() { 45 | @Override public List call(Pair, StorageChange> pair) { 46 | return pair.first; 47 | } 48 | }); 49 | } 50 | 51 | public Observable> changeObservable() { 52 | return subject.map(new Func1, StorageChange>, StorageChange>() { 53 | @Override public StorageChange call(Pair, StorageChange> pair) { 54 | return pair.second; 55 | } 56 | }); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/util/SnapperChangeFilter.java: -------------------------------------------------------------------------------- 1 | package com.example.snapper.rx.util; 2 | 3 | import android.util.Pair; 4 | 5 | import java.util.List; 6 | 7 | import io.techery.snapper.model.Indexable; 8 | import io.techery.snapper.model.ItemRef; 9 | import io.techery.snapper.storage.StorageChange; 10 | import rx.Observable; 11 | import rx.Observable.Transformer; 12 | import rx.functions.Func1; 13 | 14 | public class SnapperChangeFilter implements Transformer, StorageChange>, Pair, StorageChange>> { 15 | 16 | private final Func1, StorageChange>, Pair, StorageChange>> filter; 17 | 18 | public SnapperChangeFilter(Func1 predicate) { 19 | this.filter = createFilter(predicate); 20 | } 21 | 22 | @Override 23 | public Observable, StorageChange>> call(Observable, StorageChange>> source) { 24 | return source.map(this.filter::call); 25 | 26 | } 27 | 28 | private Func1, StorageChange>, Pair, StorageChange>> createFilter(Func1 predicate) { 29 | return pair -> { 30 | List result = Observable.from(pair.first).filter(predicate).toList().toBlocking().first(); 31 | StorageChange storageChange; 32 | List> added = Observable.from(pair.second.getAdded()) 33 | .filter(itemRef -> predicate.call(itemRef.getValue())) 34 | .toList() 35 | .toBlocking() 36 | .first(); 37 | List> updated = Observable.from(pair.second.getUpdated()) 38 | .filter(itemRef -> predicate.call(itemRef.getValue())) 39 | .toList() 40 | .toBlocking() 41 | .first(); 42 | List> removed = Observable.from(pair.second.getRemoved()) 43 | .filter(itemRef -> predicate.call(itemRef.getValue())) 44 | .toList() 45 | .toBlocking() 46 | .first(); 47 | // 48 | storageChange = new StorageChange<>(added, updated, removed); 49 | return new Pair<>(result, storageChange); 50 | }; 51 | } 52 | 53 | public Func1, StorageChange>, Pair, StorageChange>> getFilter() { 54 | return filter; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/util/SnapperChangeMapper.java: -------------------------------------------------------------------------------- 1 | package com.example.snapper.rx.util; 2 | 3 | import android.util.Pair; 4 | 5 | import java.util.List; 6 | 7 | import io.techery.snapper.model.Indexable; 8 | import io.techery.snapper.model.ItemRef; 9 | import io.techery.snapper.storage.StorageChange; 10 | import rx.Observable; 11 | import rx.Observable.Transformer; 12 | import rx.functions.Func1; 13 | 14 | public class SnapperChangeMapper implements Transformer, StorageChange>, Pair, StorageChange>> { 15 | 16 | private final Func1 func; 17 | 18 | public SnapperChangeMapper(Func1 func) { 19 | this.func = func; 20 | } 21 | 22 | @Override 23 | public Observable, StorageChange>> call(Observable, StorageChange>> source) { 24 | return source.map(pair -> { 25 | List list = Observable.from(pair.first).map(func).toList().toBlocking().first(); 26 | List> added = Observable.from(pair.second.getAdded()) 27 | .map((ItemRef itemRef) -> new ItemRef<>(itemRef.getKey(), func.call(itemRef.getValue()))) 28 | .toList() 29 | .toBlocking() 30 | .first(); 31 | List> updated = Observable.from(pair.second.getUpdated()) 32 | .map((ItemRef itemRef) -> new ItemRef<>(itemRef.getKey(), func.call(itemRef.getValue()))) 33 | .toList() 34 | .toBlocking() 35 | .first(); 36 | List> removed = Observable.from(pair.second.getRemoved()) 37 | .map((ItemRef itemRef) -> new ItemRef<>(itemRef.getKey(), func.call(itemRef.getValue()))) 38 | .toList() 39 | .toBlocking() 40 | .first(); 41 | return new Pair<>(list, new StorageChange<>(added, updated, removed)); 42 | }); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/java/com/example/snapper/rx/util/SnapperChangeSort.java: -------------------------------------------------------------------------------- 1 | package com.example.snapper.rx.util; 2 | 3 | import android.util.Pair; 4 | 5 | import java.util.Collections; 6 | import java.util.List; 7 | 8 | import io.techery.snapper.model.Indexable; 9 | import io.techery.snapper.model.ItemRef; 10 | import io.techery.snapper.storage.StorageChange; 11 | import rx.Observable; 12 | import rx.Observable.Transformer; 13 | import rx.functions.Func1; 14 | import rx.functions.Func2; 15 | 16 | public class SnapperChangeSort implements Transformer, StorageChange>, Pair, StorageChange>> { 17 | 18 | private final Func1, StorageChange>, Pair, StorageChange>> comparator; 19 | 20 | public SnapperChangeSort(Func2 comparator) { 21 | this.comparator = createComparator(comparator); 22 | } 23 | 24 | @Override 25 | public Observable, StorageChange>> call(Observable, StorageChange>> source) { 26 | return source.map(this.comparator::call); 27 | 28 | } 29 | 30 | private Func1, StorageChange>, Pair, StorageChange>> createComparator(Func2 comparator) { 31 | return pair -> { 32 | List list = Observable.from(pair.first).toSortedList(comparator).toBlocking().first(); 33 | List> added = Collections.emptyList(); 34 | List> removed = Collections.emptyList(); 35 | List> updated = Observable.from(list).map(i -> ItemRef.make(i)).toList().toBlocking().first(); 36 | 37 | return new Pair<>(list, new StorageChange<>(added, updated, removed)); 38 | }; 39 | } 40 | 41 | public Func1, StorageChange>, Pair, StorageChange>> getComparator() { 42 | return comparator; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/project.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/techery/snapper/257c8504707879dbcd4b4c3981c2dde37f373ba3/droidsnapper-sample-rx/src/main/project.properties -------------------------------------------------------------------------------- /droidsnapper-sample-rx/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 18 | 19 |