├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── RELEASING.md ├── build.gradle ├── converters ├── gson-converter │ ├── build.gradle │ └── src │ │ ├── main │ │ └── java │ │ │ └── au │ │ │ └── com │ │ │ └── gridstone │ │ │ └── rxstore │ │ │ └── converters │ │ │ └── GsonConverter.java │ │ └── test │ │ └── kotlin │ │ └── au │ │ └── com │ │ └── gridstone │ │ └── rxstore │ │ └── converters │ │ └── GsonConverterTest.kt ├── jackson-converter │ ├── build.gradle │ └── src │ │ ├── main │ │ └── java │ │ │ └── au │ │ │ └── com │ │ │ └── gridstone │ │ │ └── rxstore │ │ │ └── converters │ │ │ └── JacksonConverter.java │ │ └── test │ │ └── java │ │ └── au │ │ └── com │ │ └── gridstone │ │ └── converters │ │ └── JacksonConverterTest.java └── moshi-converter │ ├── build.gradle │ └── src │ ├── main │ └── java │ │ └── au │ │ └── com │ │ └── gridstone │ │ └── rxstore │ │ └── converters │ │ └── MoshiConverter.java │ └── test │ └── kotlin │ └── au │ └── com │ └── gridstone │ └── rxstore │ └── converters │ └── MoshiConverterTest.kt ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── rxstore-kotlin ├── build.gradle └── src │ └── main │ └── kotlin │ └── au │ └── com │ └── gridstone │ └── rxstore │ └── StoreCreators.kt ├── rxstore ├── build.gradle └── src │ ├── main │ └── java │ │ └── au │ │ └── com │ │ └── gridstone │ │ └── rxstore │ │ ├── Converter.java │ │ ├── ConverterException.java │ │ ├── ListStore.java │ │ ├── RealListStore.java │ │ ├── RealValueStore.java │ │ ├── RxStore.java │ │ ├── ThrowingRunnable.java │ │ ├── Utils.java │ │ └── ValueStore.java │ └── test │ └── kotlin │ └── au │ └── com │ └── gridstone │ └── rxstore │ ├── ListStoreTest.kt │ ├── TestData.kt │ └── ValueStoreTest.kt ├── sample ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── example │ └── rxstore │ └── RxStoreExample.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | local.properties 3 | .idea 4 | .DS_Store 5 | build 6 | *.iml 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk8 5 | 6 | script: 7 | - ./gradlew clean build check 8 | 9 | notifications: 10 | email: false 11 | 12 | sudo: false 13 | 14 | cache: 15 | directories: 16 | - $HOME/.gradle 17 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | Version 6.0.2 *(2019-05-17)* 4 | ---------------------------- 5 | * Bump gradle and kotlin gradle plugin versions. 6 | 7 | Version 6.0.1 *(2019-05-10)* 8 | ---------------------------- 9 | * Update to Gradle 5.0. 10 | * Bump dependency versions. 11 | * Add instructions for using library with RxJava1 to README. 12 | 13 | Version 6.0.0 *(2017-04-19)* 14 | ---------------------------- 15 | * Migrate to RxJava2. (Thanks @Altoyyr) 16 | - `ValueStore.observe()` now returns `Observable>`, wrapping the fact that the store may contain `null`. 17 | - `ValueStore.get()` now returns a `Maybe`, as there may not be a value in the store. 18 | * All non `observe***()` methods now have a variant that takes a `Scheduler`, allowing for fire and forget calls but still controlling `Scheduler` execution. 19 | * Remove `StoreProvider`. `ListStore` and `ValueStore` are now created by calling `RxStore.list()` and `RxStore.value()`. 20 | * Remove `StoreProvider.Builder` and enforcement of a single `Scheduler` for all store interactions. 21 | * Remove `delete()` method from stores, as it was dumb and `clear()` is sufficient. 22 | * Replace Jetbrains' nullability annotations with RxJava2's inbuilt annotations. 23 | * Converters now write to temporary files to prevent corruption. (Thanks @corcoran) 24 | 25 | Version 5.1.1 *(2017-02-06)* 26 | ---------------------------- 27 | * Fix `observeRemoveFromList()` missing `onSuccess` call. 28 | 29 | Version 5.1.0 *(2017-01-16)* 30 | ---------------------------- 31 | * Add `removeFromList()` variant that takes a predicate function. 32 | * Add `addOrReplace()` method. 33 | * Fix `observeReplace` not producing an item. 34 | 35 | Version 5.0.5 *(2017-01-13)* 36 | ---------------------------- 37 | * Fix write lock being unlocked when it shouldn't. 38 | 39 | Version 5.0.4 *(2016-12-21)* 40 | ---------------------------- 41 | * Fix `observeAddToList()` and `observeRemoveFromList()` not actually emitting modified lists. 42 | 43 | Version 5.0.3 *(2016-09-14)* 44 | ---------------------------- 45 | * Fix potential race conditions in `ListStore's` utility methods. 46 | 47 | Version 5.0.2 *(2016-05-20)* 48 | ---------------------------- 49 | * Fix Android compatibility by switching to jetbrains annotations to `annotations-java5`. 50 | 51 | Version 5.0.1 *(2016-05-19)* 52 | ---------------------------- 53 | * Fix artifacts being built against Java 8 instead of 1.6. 54 | 55 | Version 5.0.0 *(2016-05-17)* 56 | ---------------------------- 57 | * Replace `RxStore` with `StoreProvider` 58 | * Stores have convenience fire-and-forget methods 59 | * Stores can be observed 60 | * Converters now more flexible 61 | * Add `MoshiConverter` 62 | 63 | Version 4.0.0 *(2015-09-22)* 64 | ---------------------------- 65 | * Project renamed from G-Rex to RxStore 66 | * No more separate artifact for Android (it's now an optional dependency of RxStore) 67 | * Builders instead of public constructors for `RxStore` (previously known as `GRexPersister`) 68 | 69 | Version 3.0.0 *(2015-05-01)* 70 | ---------------------------- 71 | * G-Rex is no longer tied to Android, allowing you to unleash dino persistence on desktop Java 72 | * API break: `grex-android` artifact has been introduced. `grex` artifact is now used for plain Java 73 | 74 | Version 2.0.0 *(2015-02-23)* 75 | ---------------------------- 76 | * API break: `GRexPersister.get()` and `getList()` now return empty `Observables` if nothing is found at the key 77 | 78 | Version 1.1.0 *(2014-12-05)* 79 | ---------------------------- 80 | * Support for `Converter`, allowing for custom serialization formats 81 | * New grex-gson-converter artifact 82 | * New grex-jackson-converter artifact 83 | * API break: `GRexPersister` now must have a `Converter` provided in its constructor 84 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing 2 | ============ 3 | 4 | If you would like to contribute code to RxStore you can do so through GitHub by 5 | forking the repository and sending a pull request. 6 | 7 | When submitting code, please make every effort to follow existing conventions 8 | and style in order to keep the code as readable as possible. If you are using 9 | IntelliJ or Android Studio, you can make use of [Square's code styles](https://github.com/square/java-code-styles). -------------------------------------------------------------------------------- /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 | RxStore (Deprecated ⚠️) 2 | ------- 3 | 4 | This library is deprecated. Please migrate to [KStore](https://github.com/xxfast/KStore) and use [kotlinx-coroutines-rx2](https://github.com/Kotlin/kotlinx.coroutines/tree/master/reactive/kotlinx-coroutines-rx2) adapters 5 | 6 | A tiny library that assists in saving and restoring objects to and from disk using [RxJava](https://github.com/ReactiveX/RxJava), and observing changes over time. 7 | 8 | This library now targets RxJava2. If you're using RxJava1 then take a look at a [version 5.1.1](https://github.com/Gridstone/RxStore/tree/v5.1.1). 9 | 10 | Details 11 | ------- 12 | 13 | RxStore is a simple persistence framework for those already making use of RxJava2 in their projects. There are many occasions where you don't need the complexity introduced by a database; you just require a simple put/get API. 14 | 15 | We have found this particularly useful on Android, where there are [many options](http://developer.android.com/guide/topics/data/data-storage.html), but none of them quite right... 16 | 17 | * Simple key/value pair? [SharedPreferences](http://developer.android.com/reference/android/content/SharedPreferences.html) makes that simple. 18 | * Elaborate interconnected data sets? [SQLite](http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html) can help you. 19 | * Everything else? We just want to put and get objects from disk with minimal overhead. 20 | 21 | By design, RxStore lets you use whatever serialization format you prefer, so long as you provide a valid [`Converter`](https://github.com/Gridstone/RxStore/blob/master/rxstore/src/main/java/au/com/gridstone/rxstore/Converter.java). Converters for [Moshi](https://github.com/square/moshi), [Gson](https://code.google.com/p/google-gson/) and [Jackson](https://github.com/FasterXML/jackson) are provided out of the box, and pull requests for more are always welcome! 22 | 23 | Leaning on RxJava, RxStore can help alleviate some threading concerns when reading and writing to disk, and allows for some pretty nifty method chaining once the operation completes. It also lets you observe changes as you write new values into stores. 24 | 25 | Usage 26 | ----- 27 | 28 | ### Creating Stores 29 | 30 | There are two kinds of stores: 31 | - `ValueStore` lets you write, read, and observe changes to a single value you want to persist. 32 | - `ListStore` does the same but for many values, and has convenience methods for adding and removing individual items in the list. 33 | 34 | Say we have a model class called `Person` 35 | ```java 36 | public final class Person { 37 | public final String name; 38 | public final int age; 39 | } 40 | ``` 41 | 42 | To persist a single `Person`, we must first create a `ValueStore`. 43 | 44 | ```java 45 | ValueStore store = RxStore.value(file, converter, Person.class); 46 | ``` 47 | 48 | In addition to the type we must also provide a `File` and a `Converter`. The `File` gives the object a place to live on disk, and the `Converter` dictates how it's saved and restored. You can make your own `Converter` or use [one we prepared earlier](https://github.com/Gridstone/RxStore/tree/master/converters). 49 | 50 | ### Storing Data 51 | 52 | There are two ways we can add a `Person` to our store: `store.put(person)` or `store.observePut(person)`. `put()` is a fire-and-forget method that will asynchronously write the value to disk. `observePut()` returns an RxJava `Single` that must be subscribed to in order for the write operation to begin. This is useful when incorporating the write operation into a chain, or would like to know when a write operation has completed. 53 | 54 | Perhaps you're making use of Square's [Retrofit](http://square.github.io/retrofit/). You could download and persist data in a single Rx chain. 55 | 56 | ```java 57 | webServices.getPerson() 58 | .flatMap((person) -> store.observePut(person)) 59 | .subscribe((person) -> { 60 | // Do something with newly downloaded and persisted person. 61 | }); 62 | ``` 63 | 64 | `ListStore` is useful if you wanted to store many people. In addition to `put(people)` it also has some handy methods such as `add(person)` and `remove(person)`. 65 | 66 | ### Retrieving Data 67 | 68 | When retrieving from a `ValueStore` we can use `store.get()` or `store.blockingGet()`. The former returns a `Maybe`, as there may not be a current value. The latter blocks until the disk read and deserialization is complete, and returns a nullable value. 69 | 70 | `ListStore` behaves slightly differently. `get()` returns a `Single`, as empty stores can be represented by an immutable empty `List`. `blockingGet()` will always return a non-null `List`. 71 | 72 | 73 | ### Observing Data 74 | 75 | Another handy trick is to observe a store change over time. Calling `store.observe()` will give you an Rx `Observable`. This `Observable` will immediately deliver the current value of the store upon subscription, and will then deliver updated values if changes occur in `onNext()`. 76 | 77 | It's worth noting that `valueStore.observe()` does not return `Observable`, but rather `Observable>`. This is because the store cannot use null to represent the absence of a value, and must wrap the update in a non-null object. 78 | 79 | `listStore.observe()` however does return `Observable>`, as an empty `ListStore` can be represented by an immutable empty `List`. 80 | 81 | Kotlin 82 | ------ 83 | 84 | If you're working in Kotlin, there are also two convenient functions provided in the `rxstore-kotlin` artifact that make use of reified type parameters. This removes the need to pass the `Type` in the store initialisation methods. 85 | 86 | ```kotlin 87 | val personStore = storeProvider.valueStore(file, converter) 88 | val peopleStore = storeProvider.listStore(file, converter) 89 | ``` 90 | 91 | Download 92 | -------- 93 | 94 | All artifacts are up on Maven Central. 95 | 96 | For the base library 97 | ```groovy 98 | compile 'au.com.gridstone.rxstore:rxstore:6.0.2' 99 | ``` 100 | For the kotlin convenience functions 101 | ```groovy 102 | compile 'au.com.gridstone.rxstore:rxstore-kotlin:6.0.2' 103 | ``` 104 | For the Moshi converter 105 | ```groovy 106 | compile 'au.com.gridstone.rxstore:converter-moshi:6.0.2' 107 | ``` 108 | For the Gson converter 109 | ```groovy 110 | compile 'au.com.gridstone.rxstore:converter-gson:6.0.2' 111 | ``` 112 | For the Jackson converter 113 | ```groovy 114 | compile 'au.com.gridstone.rxstore:converter-jackson:6.0.2' 115 | ``` 116 | 117 | License 118 | -------- 119 | 120 | Copyright 2017 GRIDSTONE 121 | 122 | Licensed under the Apache License, Version 2.0 (the "License"); 123 | you may not use this file except in compliance with the License. 124 | You may obtain a copy of the License at 125 | 126 | http://www.apache.org/licenses/LICENSE-2.0 127 | 128 | Unless required by applicable law or agreed to in writing, software 129 | distributed under the License is distributed on an "AS IS" BASIS, 130 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 131 | See the License for the specific language governing permissions and 132 | limitations under the License. 133 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | Releasing 2 | ======== 3 | 4 | 1. Change the version in `gradle.properties` to a non-SNAPSHOT version. 5 | 2. Update the `CHANGELOG.md` for the impending release. 6 | 3. Update the `README.md` with the new version. 7 | 4. `git commit -am "Prepare for release X.Y."` (where X.Y is the new version) 8 | 5. `git tag -a X.Y -m "Version X.Y"` (where X.Y is the new version) 9 | 6. `./gradlew clean bintrayUpload` 10 | 7. Update the `gradle.properties` to the next SNAPSHOT version. 11 | 8. `git commit -am "Prepare next development version."` 12 | 9. `git push && git push --tags` 13 | 10. Visit [Bintray](https://bintray.com/gridstone/RxStore/rxstore/view) and publish the artifacts. 14 | 11. Sync to Maven Central. 15 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2018 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | } 21 | } 22 | 23 | allprojects { 24 | repositories { 25 | jcenter() 26 | } 27 | 28 | group = GROUP 29 | version = VERSION_NAME 30 | 31 | if (JavaVersion.current().isJava8Compatible()) { 32 | tasks.withType(Javadoc) { 33 | // disable the crazy super-strict doclint tool in Java 8 34 | options.addStringOption('Xdoclint:none', '-quiet') 35 | } 36 | } 37 | } 38 | 39 | ext { 40 | rxJava = 'io.reactivex.rxjava2:rxjava:2.2.4' 41 | junit = 'junit:junit:4.12' 42 | truth = 'com.google.truth:truth:0.42' 43 | gson = 'com.google.code.gson:gson:2.8.5' 44 | jackson = 'com.fasterxml.jackson.core:jackson-databind:2.9.7' 45 | moshi = 'com.squareup.moshi:moshi:1.8.0' 46 | kotlinPlugin = 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.31' 47 | kotlinStdlib = 'org.jetbrains.kotlin:kotlin-stdlib:1.3.11' 48 | bintrayPlugin = 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4' 49 | } 50 | -------------------------------------------------------------------------------- /converters/gson-converter/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2018 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | } 21 | 22 | dependencies { 23 | classpath rootProject.ext.kotlinPlugin 24 | classpath rootProject.ext.bintrayPlugin 25 | } 26 | } 27 | 28 | apply plugin: 'java' 29 | apply plugin: 'kotlin' 30 | apply plugin: 'maven-publish' 31 | apply plugin: 'com.jfrog.bintray' 32 | 33 | sourceCompatibility = 1.6 34 | targetCompatibility = 1.6 35 | 36 | repositories { 37 | jcenter() 38 | } 39 | 40 | dependencies { 41 | api project(':rxstore') 42 | implementation rootProject.ext.gson 43 | implementation rootProject.ext.rxJava 44 | 45 | testImplementation rootProject.ext.junit 46 | testImplementation rootProject.ext.truth 47 | testImplementation rootProject.ext.kotlinStdlib 48 | } 49 | 50 | task javadocJar(type: Jar) { 51 | classifier = 'javadoc' 52 | from javadoc 53 | } 54 | 55 | task sourcesJar(type: Jar) { 56 | classifier = 'sources' 57 | from sourceSets.main.allSource 58 | } 59 | 60 | artifacts { 61 | archives javadocJar, sourcesJar 62 | } 63 | 64 | publishing { 65 | publications { 66 | GsonConverter(MavenPublication) { 67 | from components.java 68 | groupId GROUP 69 | artifactId 'converter-gson' 70 | version VERSION_NAME 71 | artifact sourcesJar 72 | artifact javadocJar 73 | 74 | pom.withXml { 75 | asNode().children().last() + { 76 | resolveStrategy = Closure.DELEGATE_FIRST 77 | name 'RxStore Gson Converter' 78 | description DESCRIPTION 79 | url PROJECT_URL 80 | developers { 81 | developer { 82 | id POM_DEVELOPER_ID 83 | name POM_DEVELOPER_NAME 84 | } 85 | } 86 | licenses { 87 | license { 88 | name POM_LICENCE_NAME 89 | url POM_LICENCE_URL 90 | distribution POM_LICENCE_DIST 91 | } 92 | } 93 | scm { 94 | url PROJECT_URL 95 | connection POM_SCM_CONNECTION 96 | developerConnection POM_SCM_DEV_CONNECTION 97 | } 98 | } 99 | } 100 | } 101 | } 102 | } 103 | 104 | bintray { 105 | user = System.getenv('BINTRAY_USER') 106 | key = System.getenv('BINTRAY_KEY') 107 | publications = ['GsonConverter'] 108 | pkg { 109 | repo = BINTRAY_REPO 110 | name = BINTRAY_NAME 111 | userOrg = ORGANISATION 112 | licenses = [LICENSE] 113 | desc = DESCRIPTION 114 | websiteUrl = PROJECT_URL 115 | issueTrackerUrl = ISSUE_TRACKER_URL 116 | vcsUrl = PROJECT_URL 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /converters/gson-converter/src/main/java/au/com/gridstone/rxstore/converters/GsonConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore.converters; 18 | 19 | import au.com.gridstone.rxstore.Converter; 20 | import au.com.gridstone.rxstore.ConverterException; 21 | import com.google.gson.Gson; 22 | import java.io.File; 23 | import java.io.FileReader; 24 | import java.io.FileWriter; 25 | import java.io.Reader; 26 | import java.io.Writer; 27 | import java.lang.reflect.Type; 28 | 29 | /** 30 | * A {@link Converter} that uses {@link Gson} to get the job done. 31 | */ 32 | public class GsonConverter implements Converter { 33 | private Gson gson; 34 | 35 | public GsonConverter() { 36 | this(new Gson()); 37 | } 38 | 39 | public GsonConverter(Gson gson) { 40 | this.gson = gson; 41 | } 42 | 43 | @Override public void write(T data, Type type, File file) throws ConverterException { 44 | try { 45 | Writer writer = new FileWriter(file); 46 | gson.toJson(data, type, writer); 47 | writer.close(); 48 | } catch (Exception e) { 49 | throw new ConverterException(e); 50 | } 51 | } 52 | 53 | @Override public T read(File file, Type type) throws ConverterException { 54 | try { 55 | Reader reader = new FileReader(file); 56 | T value = gson.fromJson(reader, type); 57 | reader.close(); 58 | return value; 59 | } catch (Exception e) { 60 | throw new ConverterException(e); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /converters/gson-converter/src/test/kotlin/au/com/gridstone/rxstore/converters/GsonConverterTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore.converters 18 | 19 | import au.com.gridstone.rxstore.RxStore 20 | import com.google.common.truth.Truth.assertThat 21 | import io.reactivex.schedulers.Schedulers 22 | import org.junit.Rule 23 | import org.junit.Test 24 | import org.junit.rules.TemporaryFolder 25 | 26 | class GsonConverterTest { 27 | @Rule @JvmField val tempDir = TemporaryFolder().apply { create() } 28 | 29 | @Test fun convertValue() { 30 | val store = RxStore.value(tempDir.newFile(), GsonConverter(), TestData::class.java) 31 | assertThat(store.blockingGet()).isNull() 32 | 33 | store.put(TestData("1", 1), Schedulers.trampoline()) 34 | assertThat(store.blockingGet()).isEqualTo(TestData("1", 1)) 35 | } 36 | 37 | @Test fun convertList() { 38 | val store = RxStore.list(tempDir.newFile(), GsonConverter(), TestData::class.java) 39 | assertThat(store.blockingGet()).isEmpty() 40 | 41 | val list = listOf(TestData("1", 1), TestData("2", 2)) 42 | store.put(list, Schedulers.trampoline()) 43 | assertThat(store.blockingGet()).containsExactly(TestData("1", 1), TestData("2", 2)) 44 | } 45 | 46 | data class TestData(val string: String, val integer: Int) 47 | } -------------------------------------------------------------------------------- /converters/jackson-converter/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2018 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | } 21 | 22 | dependencies { 23 | classpath rootProject.ext.kotlinPlugin 24 | classpath rootProject.ext.bintrayPlugin 25 | } 26 | } 27 | 28 | apply plugin: 'java' 29 | apply plugin: 'java-library' 30 | apply plugin: 'maven-publish' 31 | apply plugin: 'com.jfrog.bintray' 32 | 33 | sourceCompatibility = 1.6 34 | targetCompatibility = 1.6 35 | 36 | repositories { 37 | jcenter() 38 | } 39 | 40 | dependencies { 41 | api project(':rxstore') 42 | implementation rootProject.ext.jackson 43 | implementation rootProject.ext.rxJava 44 | 45 | testImplementation rootProject.ext.junit 46 | testImplementation rootProject.ext.truth 47 | } 48 | 49 | task javadocJar(type: Jar) { 50 | classifier = 'javadoc' 51 | from javadoc 52 | } 53 | 54 | task sourcesJar(type: Jar) { 55 | classifier = 'sources' 56 | from sourceSets.main.allSource 57 | } 58 | 59 | artifacts { 60 | archives javadocJar, sourcesJar 61 | } 62 | 63 | publishing { 64 | publications { 65 | JacksonConverter(MavenPublication) { 66 | from components.java 67 | groupId GROUP 68 | artifactId 'converter-jackson' 69 | version VERSION_NAME 70 | artifact sourcesJar 71 | artifact javadocJar 72 | 73 | pom.withXml { 74 | asNode().children().last() + { 75 | resolveStrategy = Closure.DELEGATE_FIRST 76 | name 'RxStore Jackson Converter' 77 | description DESCRIPTION 78 | url PROJECT_URL 79 | developers { 80 | developer { 81 | id POM_DEVELOPER_ID 82 | name POM_DEVELOPER_NAME 83 | } 84 | } 85 | licenses { 86 | license { 87 | name POM_LICENCE_NAME 88 | url POM_LICENCE_URL 89 | distribution POM_LICENCE_DIST 90 | } 91 | } 92 | scm { 93 | url PROJECT_URL 94 | connection POM_SCM_CONNECTION 95 | developerConnection POM_SCM_DEV_CONNECTION 96 | } 97 | } 98 | } 99 | } 100 | } 101 | } 102 | 103 | bintray { 104 | user = System.getenv('BINTRAY_USER') 105 | key = System.getenv('BINTRAY_KEY') 106 | publications = ['JacksonConverter'] 107 | pkg { 108 | repo = BINTRAY_REPO 109 | name = BINTRAY_NAME 110 | userOrg = ORGANISATION 111 | licenses = [LICENSE] 112 | desc = DESCRIPTION 113 | websiteUrl = PROJECT_URL 114 | issueTrackerUrl = ISSUE_TRACKER_URL 115 | vcsUrl = PROJECT_URL 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /converters/jackson-converter/src/main/java/au/com/gridstone/rxstore/converters/JacksonConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore.converters; 18 | 19 | import au.com.gridstone.rxstore.Converter; 20 | import au.com.gridstone.rxstore.ConverterException; 21 | import com.fasterxml.jackson.databind.JavaType; 22 | import com.fasterxml.jackson.databind.ObjectMapper; 23 | import java.io.File; 24 | import java.io.FileReader; 25 | import java.io.IOException; 26 | import java.io.Reader; 27 | import java.lang.reflect.Type; 28 | 29 | /** 30 | * A {@link Converter} that uses a Jackson {@link ObjectMapper} to get the 31 | * job done. 32 | */ 33 | public class JacksonConverter implements Converter { 34 | private final ObjectMapper objectMapper; 35 | 36 | public JacksonConverter() { 37 | this(new ObjectMapper()); 38 | } 39 | 40 | public JacksonConverter(ObjectMapper objectMapper) { 41 | this.objectMapper = objectMapper; 42 | } 43 | 44 | @Override public void write(T data, Type type, File file) throws ConverterException { 45 | try { 46 | objectMapper.writeValue(file, data); 47 | } catch (IOException e) { 48 | throw new ConverterException(e); 49 | } 50 | } 51 | 52 | @Override public T read(File file, Type type) throws ConverterException { 53 | JavaType javaType = objectMapper.getTypeFactory().constructType(type); 54 | 55 | try { 56 | Reader reader = new FileReader(file); 57 | T value; 58 | 59 | if (!reader.ready()) { 60 | value = null; 61 | } else { 62 | value = objectMapper.readValue(reader, javaType); 63 | } 64 | 65 | reader.close(); 66 | return value; 67 | } catch (Exception e) { 68 | throw new ConverterException(e); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /converters/jackson-converter/src/test/java/au/com/gridstone/converters/JacksonConverterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.converters; 18 | 19 | import au.com.gridstone.rxstore.ListStore; 20 | import au.com.gridstone.rxstore.RxStore; 21 | import au.com.gridstone.rxstore.ValueStore; 22 | import au.com.gridstone.rxstore.converters.JacksonConverter; 23 | import io.reactivex.schedulers.Schedulers; 24 | import java.io.IOException; 25 | import java.util.Arrays; 26 | import java.util.List; 27 | import org.junit.Rule; 28 | import org.junit.Test; 29 | import org.junit.rules.TemporaryFolder; 30 | 31 | import static com.google.common.truth.Truth.assertThat; 32 | 33 | /** 34 | * This must remain as Java rather than Kotlin because vanilla Jackson seems to have issues with 35 | * Kotlin's data classes. 36 | */ 37 | public final class JacksonConverterTest { 38 | @Rule public TemporaryFolder tempDir = new TemporaryFolder(); 39 | 40 | @Test public void convertValue() throws IOException { 41 | ValueStore store = 42 | RxStore.value(tempDir.newFile(), new JacksonConverter(), TestData.class); 43 | 44 | assertThat(store.blockingGet()).isNull(); 45 | 46 | TestData value = new TestData("Test1", 1); 47 | store.put(value, Schedulers.trampoline()); 48 | assertThat(store.blockingGet()).isEqualTo(value); 49 | } 50 | 51 | @Test public void convertList() throws IOException { 52 | ListStore store = 53 | RxStore.list(tempDir.newFile(), new JacksonConverter(), TestData.class); 54 | 55 | assertThat(store.blockingGet()).isEmpty(); 56 | 57 | List list = Arrays.asList(new TestData("Test1", 1), new TestData("Test2", 2)); 58 | store.put(list, Schedulers.trampoline()); 59 | assertThat(store.blockingGet()).isEqualTo(list); 60 | } 61 | 62 | public static class TestData { 63 | public String string; 64 | public int integer; 65 | 66 | public TestData() { 67 | } 68 | 69 | public TestData(String string, int integer) { 70 | this.string = string; 71 | this.integer = integer; 72 | } 73 | 74 | @Override public boolean equals(Object o) { 75 | if (!(o instanceof TestData)) { 76 | return false; 77 | } 78 | 79 | TestData otherData = (TestData) o; 80 | 81 | if (string != null) { 82 | return string.equals(otherData.string) && integer == otherData.integer; 83 | } 84 | 85 | return otherData.string == null && integer == otherData.integer; 86 | } 87 | 88 | @Override public String toString() { 89 | return string + "," + integer; 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /converters/moshi-converter/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2018 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | } 21 | 22 | dependencies { 23 | classpath rootProject.ext.kotlinPlugin 24 | classpath rootProject.ext.bintrayPlugin 25 | } 26 | } 27 | 28 | apply plugin: 'java' 29 | apply plugin: 'kotlin' 30 | apply plugin: 'maven-publish' 31 | apply plugin: 'com.jfrog.bintray' 32 | 33 | sourceCompatibility = 1.6 34 | targetCompatibility = 1.6 35 | 36 | repositories { 37 | jcenter() 38 | } 39 | 40 | dependencies { 41 | api project(':rxstore') 42 | implementation rootProject.ext.moshi 43 | implementation rootProject.ext.rxJava 44 | 45 | testImplementation rootProject.ext.junit 46 | testImplementation rootProject.ext.truth 47 | testImplementation rootProject.ext.kotlinStdlib 48 | } 49 | 50 | task javadocJar(type: Jar) { 51 | classifier = 'javadoc' 52 | from javadoc 53 | } 54 | 55 | task sourcesJar(type: Jar) { 56 | classifier = 'sources' 57 | from sourceSets.main.allSource 58 | } 59 | 60 | artifacts { 61 | archives javadocJar, sourcesJar 62 | } 63 | 64 | publishing { 65 | publications { 66 | MoshiConverter(MavenPublication) { 67 | from components.java 68 | groupId GROUP 69 | artifactId 'converter-moshi' 70 | version VERSION_NAME 71 | artifact sourcesJar 72 | artifact javadocJar 73 | 74 | pom.withXml { 75 | asNode().children().last() + { 76 | resolveStrategy = Closure.DELEGATE_FIRST 77 | name 'RxStore Moshi Converter' 78 | description DESCRIPTION 79 | url PROJECT_URL 80 | developers { 81 | developer { 82 | id POM_DEVELOPER_ID 83 | name POM_DEVELOPER_NAME 84 | } 85 | } 86 | licenses { 87 | license { 88 | name POM_LICENCE_NAME 89 | url POM_LICENCE_URL 90 | distribution POM_LICENCE_DIST 91 | } 92 | } 93 | scm { 94 | url PROJECT_URL 95 | connection POM_SCM_CONNECTION 96 | developerConnection POM_SCM_DEV_CONNECTION 97 | } 98 | } 99 | } 100 | } 101 | } 102 | } 103 | 104 | bintray { 105 | user = System.getenv('BINTRAY_USER') 106 | key = System.getenv('BINTRAY_KEY') 107 | publications = ['MoshiConverter'] 108 | pkg { 109 | repo = BINTRAY_REPO 110 | name = BINTRAY_NAME 111 | userOrg = ORGANISATION 112 | licenses = [LICENSE] 113 | desc = DESCRIPTION 114 | websiteUrl = PROJECT_URL 115 | issueTrackerUrl = ISSUE_TRACKER_URL 116 | vcsUrl = PROJECT_URL 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /converters/moshi-converter/src/main/java/au/com/gridstone/rxstore/converters/MoshiConverter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore.converters; 18 | 19 | import au.com.gridstone.rxstore.Converter; 20 | import au.com.gridstone.rxstore.ConverterException; 21 | import com.squareup.moshi.JsonAdapter; 22 | import com.squareup.moshi.Moshi; 23 | import java.io.File; 24 | import java.io.IOException; 25 | import java.lang.reflect.Type; 26 | import okio.BufferedSink; 27 | import okio.BufferedSource; 28 | import okio.Okio; 29 | 30 | public class MoshiConverter implements Converter { 31 | private final Moshi moshi; 32 | 33 | public MoshiConverter() { 34 | this(new Moshi.Builder().build()); 35 | } 36 | 37 | public MoshiConverter(Moshi moshi) { 38 | this.moshi = moshi; 39 | } 40 | 41 | @Override public void write(T data, Type type, File file) throws ConverterException { 42 | try { 43 | JsonAdapter adapter = moshi.adapter(type); 44 | BufferedSink sink = Okio.buffer(Okio.sink(file)); 45 | adapter.toJson(sink, data); 46 | sink.close(); 47 | } catch (IOException e) { 48 | throw new ConverterException(e); 49 | } 50 | } 51 | 52 | @Override public T read(File file, Type type) { 53 | try { 54 | JsonAdapter adapter = moshi.adapter(type); 55 | BufferedSource source = Okio.buffer(Okio.source(file)); 56 | T value; 57 | 58 | if (source.exhausted()) { 59 | value = null; 60 | } else { 61 | value = adapter.nullSafe().fromJson(source); 62 | } 63 | 64 | source.close(); 65 | return value; 66 | } catch (Exception e) { 67 | throw new ConverterException(e); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /converters/moshi-converter/src/test/kotlin/au/com/gridstone/rxstore/converters/MoshiConverterTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore.converters 18 | 19 | import au.com.gridstone.rxstore.RxStore 20 | import com.google.common.truth.Truth.assertThat 21 | import io.reactivex.schedulers.Schedulers 22 | import org.junit.Rule 23 | import org.junit.Test 24 | import org.junit.rules.TemporaryFolder 25 | 26 | class MoshiConverterTest { 27 | @Rule @JvmField val tempDir = TemporaryFolder().apply { create() } 28 | 29 | @Test fun convertValue() { 30 | val store = RxStore.value(tempDir.newFile(), MoshiConverter(), TestData::class.java) 31 | assertThat(store.blockingGet()).isNull() 32 | 33 | store.put(TestData("1", 1), Schedulers.trampoline()) 34 | assertThat(store.blockingGet()).isEqualTo(TestData("1", 1)) 35 | } 36 | 37 | @Test fun convertList() { 38 | val store = RxStore.list(tempDir.newFile(), MoshiConverter(), TestData::class.java) 39 | assertThat(store.blockingGet()).isEmpty() 40 | 41 | val list = listOf(TestData("1", 1), TestData("2", 2)) 42 | store.put(list, Schedulers.trampoline()) 43 | assertThat(store.blockingGet()).containsExactly(TestData("1", 1), TestData("2", 2)) 44 | } 45 | 46 | data class TestData(val string: String, val integer: Int) 47 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | VERSION_NAME=6.0.3-SNAPSHOT 2 | GROUP=au.com.gridstone.rxstore 3 | DESCRIPTION=A tiny library that assists in saving and restoring objects to disk using RxJava. 4 | PROJECT_URL=https://github.com/Gridstone/RxStore 5 | ISSUE_TRACKER_URL=https://github.com/Gridstone/RxStore/issues 6 | LICENSE=Apache-2.0 7 | ORGANISATION=gridstone 8 | BINTRAY_REPO=RxStore 9 | BINTRAY_NAME=rxstore 10 | 11 | POM_SCM_CONNECTION=git@github.com:Gridstone/RxStore.git 12 | POM_SCM_DEV_CONNECTION=git@github.com:Gridstone/RxStore.git 13 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 14 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 15 | POM_LICENCE_DIST=repo 16 | POM_DEVELOPER_ID=gridstone 17 | POM_DEVELOPER_NAME=Gridstone 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gridstone/RxStore/d3ade0b36728e49b3b8f19e9f8578f7745bdb08b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Dec 03 08:58:38 EST 2014 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip 7 | -------------------------------------------------------------------------------- /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 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /rxstore-kotlin/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2018 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | } 21 | 22 | dependencies { 23 | classpath rootProject.ext.kotlinPlugin 24 | classpath rootProject.ext.bintrayPlugin 25 | } 26 | } 27 | 28 | apply plugin: 'java' 29 | apply plugin: 'kotlin' 30 | apply plugin: 'maven-publish' 31 | apply plugin: 'com.jfrog.bintray' 32 | 33 | sourceCompatibility = 1.6 34 | targetCompatibility = 1.6 35 | 36 | dependencies { 37 | implementation rootProject.ext.kotlinStdlib 38 | api project(':rxstore') 39 | } 40 | 41 | defaultTasks 'jar' 42 | 43 | task sourcesJar(type: Jar, dependsOn: classes) { 44 | classifier = 'sources' 45 | from sourceSets.main.allSource 46 | } 47 | 48 | task javadocJar(type: Jar) { 49 | classifier = 'javadoc' 50 | from javadoc 51 | } 52 | 53 | artifacts { 54 | archives javadocJar, sourcesJar 55 | } 56 | 57 | publishing { 58 | publications { 59 | RxStoreKotlin(MavenPublication) { 60 | from components.java 61 | groupId GROUP 62 | artifactId 'rxstore-kotlin' 63 | version VERSION_NAME 64 | artifact sourcesJar 65 | artifact javadocJar 66 | 67 | pom.withXml { 68 | asNode().children().last() + { 69 | resolveStrategy = Closure.DELEGATE_FIRST 70 | name 'RxStore Kotlin Extensions' 71 | description DESCRIPTION 72 | url PROJECT_URL 73 | developers { 74 | developer { 75 | id POM_DEVELOPER_ID 76 | name POM_DEVELOPER_NAME 77 | } 78 | } 79 | licenses { 80 | license { 81 | name POM_LICENCE_NAME 82 | url POM_LICENCE_URL 83 | distribution POM_LICENCE_DIST 84 | } 85 | } 86 | scm { 87 | url PROJECT_URL 88 | connection POM_SCM_CONNECTION 89 | developerConnection POM_SCM_DEV_CONNECTION 90 | } 91 | } 92 | } 93 | } 94 | } 95 | } 96 | 97 | bintray { 98 | user = System.getenv('BINTRAY_USER') 99 | key = System.getenv('BINTRAY_KEY') 100 | publications = ['RxStoreKotlin'] 101 | pkg { 102 | repo = BINTRAY_REPO 103 | name = BINTRAY_NAME 104 | userOrg = ORGANISATION 105 | licenses = [LICENSE] 106 | desc = DESCRIPTION 107 | websiteUrl = PROJECT_URL 108 | issueTrackerUrl = ISSUE_TRACKER_URL 109 | vcsUrl = PROJECT_URL 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /rxstore-kotlin/src/main/kotlin/au/com/gridstone/rxstore/StoreCreators.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore 18 | 19 | import java.io.File 20 | 21 | inline fun createValueStore(file: File, converter: Converter): ValueStore 22 | = RxStore.value(file, converter, T::class.java) 23 | 24 | inline fun createListStore(file: File, converter: Converter): ListStore 25 | = RxStore.list(file, converter, T::class.java) 26 | -------------------------------------------------------------------------------- /rxstore/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2018 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | } 21 | 22 | dependencies { 23 | classpath rootProject.ext.kotlinPlugin 24 | classpath rootProject.ext.bintrayPlugin 25 | } 26 | } 27 | 28 | apply plugin: 'java' 29 | apply plugin: 'kotlin' 30 | apply plugin: 'maven-publish' 31 | apply plugin: 'com.jfrog.bintray' 32 | 33 | sourceCompatibility = 1.6 34 | targetCompatibility = 1.6 35 | 36 | dependencies { 37 | api rootProject.ext.rxJava 38 | 39 | testImplementation rootProject.ext.junit 40 | testImplementation rootProject.ext.truth 41 | testImplementation rootProject.ext.kotlinStdlib 42 | } 43 | 44 | task javadocJar(type: Jar) { 45 | classifier = 'javadoc' 46 | from javadoc 47 | } 48 | 49 | task sourcesJar(type: Jar) { 50 | classifier = 'sources' 51 | from sourceSets.main.allSource 52 | } 53 | 54 | artifacts { 55 | archives javadocJar, sourcesJar 56 | } 57 | 58 | publishing { 59 | publications { 60 | RxStore(MavenPublication) { 61 | from components.java 62 | groupId GROUP 63 | artifactId 'rxstore' 64 | version VERSION_NAME 65 | artifact sourcesJar 66 | artifact javadocJar 67 | 68 | pom.withXml { 69 | asNode().children().last() + { 70 | resolveStrategy = Closure.DELEGATE_FIRST 71 | name 'RxStore' 72 | description DESCRIPTION 73 | url PROJECT_URL 74 | developers { 75 | developer { 76 | id POM_DEVELOPER_ID 77 | name POM_DEVELOPER_NAME 78 | } 79 | } 80 | licenses { 81 | license { 82 | name POM_LICENCE_NAME 83 | url POM_LICENCE_URL 84 | distribution POM_LICENCE_DIST 85 | } 86 | } 87 | scm { 88 | url PROJECT_URL 89 | connection POM_SCM_CONNECTION 90 | developerConnection POM_SCM_DEV_CONNECTION 91 | } 92 | } 93 | } 94 | } 95 | } 96 | } 97 | 98 | bintray { 99 | user = System.getenv('BINTRAY_USER') 100 | key = System.getenv('BINTRAY_KEY') 101 | publications = ['RxStore'] 102 | pkg { 103 | repo = BINTRAY_REPO 104 | name = BINTRAY_NAME 105 | userOrg = ORGANISATION 106 | licenses = [LICENSE] 107 | desc = DESCRIPTION 108 | websiteUrl = PROJECT_URL 109 | issueTrackerUrl = ISSUE_TRACKER_URL 110 | vcsUrl = PROJECT_URL 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/Converter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | import io.reactivex.annotations.NonNull; 20 | import io.reactivex.annotations.Nullable; 21 | import java.io.File; 22 | import java.lang.reflect.Type; 23 | 24 | /** 25 | * Convert objects to and from serializable formats and read/write them from disk. 26 | */ 27 | public interface Converter { 28 | /** 29 | * Convert data into a serializable format and write to writer. 30 | */ 31 | void write(@Nullable T data, @NonNull Type type, @NonNull File file) 32 | throws ConverterException; 33 | 34 | /** 35 | * Pull typed data out of reader. 36 | */ 37 | @Nullable T read(@NonNull File file, @NonNull Type type) throws ConverterException; 38 | } 39 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/ConverterException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | import java.io.File; 20 | import java.lang.reflect.Type; 21 | 22 | /** 23 | * Represents something going horribly wrong when a {@link Converter} tries to 24 | * {@link Converter#read(File, Type)} or {@link Converter#write(Object, Type, File)}. 25 | */ 26 | public class ConverterException extends RuntimeException { 27 | public ConverterException() { 28 | } 29 | 30 | public ConverterException(String detailMessage) { 31 | super(detailMessage); 32 | } 33 | 34 | public ConverterException(String detailMessage, Throwable throwable) { 35 | super(detailMessage, throwable); 36 | } 37 | 38 | public ConverterException(Throwable throwable) { 39 | super(throwable); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/ListStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | import io.reactivex.Observable; 20 | import io.reactivex.Scheduler; 21 | import io.reactivex.Single; 22 | import io.reactivex.annotations.NonNull; 23 | import io.reactivex.schedulers.Schedulers; 24 | import java.util.List; 25 | 26 | /** 27 | * Store a {@code List} of homogeneous values on disk. 28 | */ 29 | public interface ListStore { 30 | /** 31 | * Retrieve the current {@code List} from this store using Rx. If this store has not had any 32 | * values written then an empty immutable {@code List} is returned by this {@link Single}. 33 | */ 34 | @NonNull Single> get(); 35 | 36 | /** 37 | * Retrieve the current {@code List} from this store in a blocking manner. This may take time. If 38 | * the store has not yet had any values written to it then this method returns an empty immutable 39 | * {@code List}. 40 | */ 41 | @NonNull List blockingGet(); 42 | 43 | /** 44 | * Write a {@code List} to this store and observe the operation. The {@code List} returned in the 45 | * {@link Single} is the {@code List} written to this store, making this useful for chaining. 46 | */ 47 | @NonNull Single> observePut(@NonNull final List list); 48 | 49 | /** 50 | * Asynchronously write a {@code List} to this store. The write operation occurs on {@link 51 | * Schedulers#io()}. If you wish to specify the {@link Scheduler} then use {@link #put(List, 52 | * Scheduler)}. 53 | */ 54 | void put(@NonNull List list); 55 | 56 | /** 57 | * Write a {@code List} to this store on a specified {@link Scheduler}. 58 | */ 59 | void put(@NonNull List list, @NonNull Scheduler scheduler); 60 | 61 | /** 62 | * Observe changes to the {@code List} in this store. {@code onNext()} will be invoked immediately 63 | * with the current {@code List} upon subscription and subsequent changes thereafter. 64 | *

65 | * When this store is empty the item delivered in {@code onNext()} is an empty immutable {@code 66 | * List}. 67 | */ 68 | @NonNull Observable> observe(); 69 | 70 | /** 71 | * Clear the {code List} in this store and observe the operation. 72 | *

73 | * The {@code List} returned by the {@link Single} is the new, empty {@code List}, making this 74 | * useful for chaining. 75 | */ 76 | @NonNull Single> observeClear(); 77 | 78 | /** 79 | * Asynchronously clear the {@code List} in this store. The clear operation occurs on {@link 80 | * Schedulers#io()}. If you wish to specify the {@link Scheduler} then use {@link 81 | * #clear(Scheduler)}. 82 | */ 83 | void clear(); 84 | 85 | /** 86 | * Clear the {@code List} from this store on a specified {@link Scheduler}. 87 | */ 88 | void clear(@NonNull Scheduler scheduler); 89 | 90 | /** 91 | * Add an item to the stored {@code List} and observe the operation. This will create a new {@code 92 | * List} if one does not currently exist. 93 | *

94 | * The {@code List} returned by the {@link Single} is the {@code List} written to this store, 95 | * making this useful for chaining. 96 | */ 97 | @NonNull Single> observeAdd(@NonNull final T value); 98 | 99 | /** 100 | * Asynchronously add an item to the stored {@code List}. The write operation occurs on {@link 101 | * Schedulers#io()}. If you wish to specify the {@link Scheduler} then use {@link #add(Object, 102 | * Scheduler)}. 103 | */ 104 | void add(@NonNull T value); 105 | 106 | /** 107 | * Add an item to the stored {@code List} on the specified {@link Scheduler}. 108 | */ 109 | void add(@NonNull T value, @NonNull Scheduler scheduler); 110 | 111 | /** 112 | * Attempt to remove an item from the {@code List} and observe the operation. This method removes 113 | * the first item for which the predicate function returns true. 114 | *

115 | * The {@code List} returned by the {@link Single} is the modified {@code List} written to this 116 | * store, making this useful for chaining. 117 | */ 118 | @NonNull Single> observeRemove(@NonNull final PredicateFunc predicateFunc); 119 | 120 | /** 121 | * Asynchronously attempt to remove an item from the {@code List}. This method removes the first 122 | * item for which the predicate function returns true. 123 | *

124 | * This operation occurs on {@link Schedulers#io()}. If you wish to specify the {@link Scheduler} 125 | * then use {@link #remove(Scheduler, PredicateFunc)}. 126 | */ 127 | void remove(@NonNull PredicateFunc predicateFunc); 128 | 129 | /** 130 | * Attempt to remove an item from the {@code List} on the specified {@link Scheduler}. This method 131 | * removes the first item for which the predicate function returns true. 132 | */ 133 | void remove(@NonNull Scheduler scheduler, @NonNull PredicateFunc predicateFunc); 134 | 135 | /** 136 | * Attempt to remove an item from the {@code List} and observe the operation. This method removes 137 | * the first item that {@code .equals()} the specified value. 138 | *

139 | * The {@code List} returned by the {@link Single} is the modified {@code List} written to this 140 | * store, making this useful for chaining. 141 | */ 142 | @NonNull Single> observeRemove(@NonNull final T value); 143 | 144 | /** 145 | * Asynchronously attempt to remove an item from the {@code List}. This method removes the first 146 | * item that {@code .equals()} the specified value. 147 | *

148 | * This operation occurs on {@link Schedulers#io()}. If you wish to specify the {@link Scheduler} 149 | * then use {@link #remove(Object, Scheduler)}. 150 | */ 151 | void remove(@NonNull final T value); 152 | 153 | /** 154 | * Attempt to remove an item from the {@code List} on the specified {@link Scheduler}. This method 155 | * removes the first item that {@code .equals()} the specified value. 156 | */ 157 | void remove(@NonNull final T value, @NonNull Scheduler scheduler); 158 | 159 | /** 160 | * Remove the item from the {@code List} at the specified position and observe the operation. 161 | *

162 | * The {@code List} returned by the {@link Single} is the modified {@code List} written to this 163 | * store, making this useful for chaining. 164 | */ 165 | @NonNull Single> observeRemove(final int position); 166 | 167 | /** 168 | * Asynchronously remove the item from the {@code List} at the specified position. 169 | *

170 | * This operation occurs on {@link Schedulers#io()}. If you wish to specify the {@link Scheduler} 171 | * then use {@link #remove(int, Scheduler)}. 172 | */ 173 | void remove(int position); 174 | 175 | /** 176 | * Remove an item from the {@code List} at the position on the specified {@link Scheduler}. 177 | */ 178 | void remove(int position, @NonNull Scheduler scheduler); 179 | 180 | /** 181 | * Attempt to replace an item from the {@code List} and observe the operation. This method 182 | * replaces the first item for which the predicate function returns true. 183 | *

184 | * The {@code List} returned by the {@link Single} is the modified {@code List} written to this 185 | * store, making this useful for chaining. 186 | */ 187 | @NonNull Single> observeReplace(@NonNull final T value, 188 | @NonNull final PredicateFunc predicateFunc); 189 | 190 | /** 191 | * Asynchronously attempt to replace an item in the {@code List}. This method replaces the first 192 | * item for which the predicate function returns true. 193 | *

194 | * This operation occurs on {@link Schedulers#io()}. If you wish to specify the {@link Scheduler} 195 | * then use {@link #replace(Object, Scheduler, PredicateFunc)}. 196 | */ 197 | void replace(@NonNull T value, @NonNull PredicateFunc predicateFunc); 198 | 199 | /** 200 | * Attempt to replace an item in the {@code List} on the specified {@link Scheduler}. This method 201 | * replaces the first item for which the predicate function returns true. 202 | */ 203 | void replace(@NonNull T value, @NonNull Scheduler scheduler, 204 | @NonNull PredicateFunc predicateFunc); 205 | 206 | /** 207 | * Add or replace an item from the {@code List} and observe the operation. This method replaces 208 | * the first item in the {@code List} for which the predicate function returns true. If no items 209 | * qualify then the item is appended to the end of the {@code List}. 210 | *

211 | * The {@code List} returned by the {@link Single} is the modified {@code List} written to this 212 | * store, making this useful for chaining. 213 | */ 214 | @NonNull Single> observeAddOrReplace(@NonNull final T value, 215 | @NonNull final PredicateFunc predicateFunc); 216 | 217 | /** 218 | * Asynchronously add or replace an item from the {@code List}. This method replaces 219 | * the first item in the {@code List} for which the predicate function returns true. If no items 220 | * qualify then the item is appended to the end of the {@code List}. 221 | *

222 | * This operation occurs on {@link Schedulers#io()}. If you wish to specify the {@link Scheduler} 223 | * then use {@link #addOrReplace(Object, Scheduler, PredicateFunc)}. 224 | */ 225 | void addOrReplace(@NonNull T value, @NonNull PredicateFunc predicateFunc); 226 | 227 | /** 228 | * Add or replace an item from the {@code List} on the specified {@link Scheduler}. This method 229 | * replaces the first item in the {@code List} for which the predicate function returns true. If 230 | * no items qualify then the item is appended to the end of the {@code List}. 231 | */ 232 | void addOrReplace(@NonNull T value, @NonNull Scheduler scheduler, 233 | @NonNull PredicateFunc predicateFunc); 234 | 235 | /** 236 | * A callback to determine if a particular value qualifies for an operation. 237 | */ 238 | interface PredicateFunc { 239 | /** 240 | * Determine if a value qualifies for a particular operation. 241 | */ 242 | boolean test(@NonNull T value); 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/RealListStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | import io.reactivex.Observable; 20 | import io.reactivex.Scheduler; 21 | import io.reactivex.Single; 22 | import io.reactivex.SingleEmitter; 23 | import io.reactivex.SingleOnSubscribe; 24 | import io.reactivex.annotations.NonNull; 25 | import io.reactivex.schedulers.Schedulers; 26 | import io.reactivex.subjects.PublishSubject; 27 | import java.io.File; 28 | import java.io.IOException; 29 | import java.lang.reflect.ParameterizedType; 30 | import java.lang.reflect.Type; 31 | import java.util.ArrayList; 32 | import java.util.Collections; 33 | import java.util.List; 34 | import java.util.concurrent.locks.ReentrantReadWriteLock; 35 | 36 | import static au.com.gridstone.rxstore.Utils.converterWrite; 37 | import static au.com.gridstone.rxstore.Utils.runInReadLock; 38 | import static au.com.gridstone.rxstore.Utils.runInWriteLock; 39 | import static au.com.gridstone.rxstore.Utils.assertNotNull; 40 | 41 | final class RealListStore implements ListStore { 42 | private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 43 | private final PublishSubject> updateSubject = PublishSubject.create(); 44 | 45 | private final File file; 46 | private final Converter converter; 47 | private final Type type; 48 | 49 | RealListStore(@NonNull File file, @NonNull Converter converter, @NonNull Type type) { 50 | assertNotNull(file, "file"); 51 | assertNotNull(converter, "converter"); 52 | assertNotNull(type, "type"); 53 | this.file = file; 54 | this.converter = converter; 55 | this.type = new ListType(type); 56 | } 57 | 58 | @Override @NonNull public Single> get() { 59 | return Single.create(new SingleOnSubscribe>() { 60 | @Override public void subscribe(final SingleEmitter> emitter) throws Exception { 61 | runInReadLock(readWriteLock, new ThrowingRunnable() { 62 | @Override public void run() throws Exception { 63 | if (!file.exists()) { 64 | emitter.onSuccess(Collections.emptyList()); 65 | return; 66 | } 67 | 68 | List list = converter.read(file, type); 69 | if (list == null) list = Collections.emptyList(); 70 | emitter.onSuccess(list); 71 | } 72 | }); 73 | } 74 | }); 75 | } 76 | 77 | @Override @NonNull public List blockingGet() { 78 | return get().blockingGet(); 79 | } 80 | 81 | @Override @NonNull public Single> observePut(@NonNull final List list) { 82 | assertNotNull(list, "list"); 83 | 84 | return Single.create(new SingleOnSubscribe>() { 85 | @Override public void subscribe(final SingleEmitter> emitter) throws Exception { 86 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 87 | @Override public void run() throws Exception { 88 | if (!file.exists() && !file.createNewFile()) { 89 | throw new IOException("Could not create file for store."); 90 | } 91 | 92 | converterWrite(list, converter, type, file); 93 | emitter.onSuccess(list); 94 | updateSubject.onNext(list); 95 | } 96 | }); 97 | } 98 | }); 99 | } 100 | 101 | @Override public void put(@NonNull List list) { 102 | put(list, Schedulers.io()); 103 | } 104 | 105 | @Override public void put(@NonNull List list, @NonNull Scheduler scheduler) { 106 | assertNotNull(scheduler, "scheduler"); 107 | observePut(list).subscribeOn(scheduler).subscribe(); 108 | } 109 | 110 | @Override @NonNull public Observable> observe() { 111 | return updateSubject.startWith(get().toObservable()); 112 | } 113 | 114 | @Override @NonNull public Single> observeClear() { 115 | return Single.create(new SingleOnSubscribe>() { 116 | @Override public void subscribe(final SingleEmitter> emitter) throws Exception { 117 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 118 | @Override public void run() throws Exception { 119 | if (file.exists() && !file.delete()) { 120 | throw new IOException("Clear operation on store failed."); 121 | } 122 | 123 | emitter.onSuccess(Collections.emptyList()); 124 | updateSubject.onNext(Collections.emptyList()); 125 | } 126 | }); 127 | } 128 | }); 129 | } 130 | 131 | @Override public void clear() { 132 | clear(Schedulers.io()); 133 | } 134 | 135 | @Override public void clear(@NonNull Scheduler scheduler) { 136 | assertNotNull(scheduler, "scheduler"); 137 | observeClear().subscribeOn(scheduler).subscribe(); 138 | } 139 | 140 | @Override @NonNull public Single> observeAdd(@NonNull final T value) { 141 | assertNotNull(value, "value"); 142 | 143 | return Single.create(new SingleOnSubscribe>() { 144 | @Override public void subscribe(final SingleEmitter> emitter) throws Exception { 145 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 146 | @Override public void run() throws Exception { 147 | if (!file.exists() && !file.createNewFile()) { 148 | throw new IOException("Could not create file for store."); 149 | } 150 | 151 | List originalList = converter.read(file, type); 152 | if (originalList == null) originalList = Collections.emptyList(); 153 | 154 | List result = new ArrayList(originalList.size() + 1); 155 | result.addAll(originalList); 156 | result.add(value); 157 | 158 | converterWrite(result, converter, type, file); 159 | emitter.onSuccess(result); 160 | updateSubject.onNext(result); 161 | } 162 | }); 163 | } 164 | }); 165 | } 166 | 167 | @Override public void add(@NonNull T value) { 168 | add(value, Schedulers.io()); 169 | } 170 | 171 | @Override public void add(@NonNull T value, @NonNull Scheduler scheduler) { 172 | assertNotNull(scheduler, "scheduler"); 173 | observeAdd(value).subscribeOn(scheduler).subscribe(); 174 | } 175 | 176 | @Override @NonNull public Single> observeRemove( 177 | @NonNull final PredicateFunc predicateFunc) { 178 | assertNotNull(predicateFunc, "predicateFunc"); 179 | 180 | return Single.create(new SingleOnSubscribe>() { 181 | @Override public void subscribe(final SingleEmitter> emitter) throws Exception { 182 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 183 | @Override public void run() throws Exception { 184 | if (!file.exists()) { 185 | emitter.onSuccess(Collections.emptyList()); 186 | return; 187 | } 188 | 189 | List originalList = converter.read(file, type); 190 | if (originalList == null) originalList = Collections.emptyList(); 191 | 192 | int indexOfItemToRemove = -1; 193 | 194 | for (int i = 0; i < originalList.size(); i++) { 195 | if (predicateFunc.test(originalList.get(i))) { 196 | indexOfItemToRemove = i; 197 | break; 198 | } 199 | } 200 | 201 | List modifiedList = new ArrayList(originalList); 202 | 203 | if (indexOfItemToRemove != -1) { 204 | modifiedList.remove(indexOfItemToRemove); 205 | converterWrite(modifiedList, converter, type, file); 206 | } 207 | 208 | emitter.onSuccess(modifiedList); 209 | updateSubject.onNext(modifiedList); 210 | } 211 | }); 212 | } 213 | }); 214 | } 215 | 216 | @Override public void remove(@NonNull PredicateFunc predicateFunc) { 217 | remove(Schedulers.io(), predicateFunc); 218 | } 219 | 220 | @Override public void remove(@NonNull Scheduler scheduler, 221 | @NonNull PredicateFunc predicateFunc) { 222 | assertNotNull(scheduler, "scheduler"); 223 | observeRemove(predicateFunc).subscribeOn(scheduler).subscribe(); 224 | } 225 | 226 | @Override @NonNull public Single> observeRemove(@NonNull final T value) { 227 | assertNotNull(value, "value"); 228 | return observeRemove(new PredicateFunc() { 229 | @Override public boolean test(T valueToRemove) { 230 | return value.equals(valueToRemove); 231 | } 232 | }); 233 | } 234 | 235 | @Override public void remove(@NonNull final T value) { 236 | remove(value, Schedulers.io()); 237 | } 238 | 239 | @Override public void remove(@NonNull final T value, @NonNull Scheduler scheduler) { 240 | assertNotNull(scheduler, "scheduler"); 241 | observeRemove(value).subscribeOn(scheduler).subscribe(); 242 | } 243 | 244 | @Override @NonNull public Single> observeRemove(final int position) { 245 | return Single.create(new SingleOnSubscribe>() { 246 | @Override public void subscribe(final SingleEmitter> emitter) throws Exception { 247 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 248 | @Override public void run() throws Exception { 249 | List originalList = converter.read(file, type); 250 | if (originalList == null) originalList = Collections.emptyList(); 251 | 252 | List modifiedList = new ArrayList(originalList); 253 | modifiedList.remove(position); 254 | 255 | converterWrite(modifiedList, converter, type, file); 256 | emitter.onSuccess(modifiedList); 257 | updateSubject.onNext(modifiedList); 258 | } 259 | }); 260 | } 261 | }); 262 | } 263 | 264 | @Override public void remove(int position) { 265 | remove(position, Schedulers.io()); 266 | } 267 | 268 | @Override public void remove(int position, @NonNull Scheduler scheduler) { 269 | assertNotNull(scheduler, "scheduler"); 270 | observeRemove(position).subscribeOn(scheduler).subscribe(); 271 | } 272 | 273 | @Override @NonNull public Single> observeReplace(@NonNull final T value, 274 | @NonNull final PredicateFunc predicateFunc) { 275 | assertNotNull(value, "value"); 276 | assertNotNull(predicateFunc, "predicateFunc"); 277 | 278 | return Single.create(new SingleOnSubscribe>() { 279 | @Override public void subscribe(final SingleEmitter> emitter) throws Exception { 280 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 281 | @Override public void run() throws Exception { 282 | if (!file.exists()) { 283 | emitter.onSuccess(Collections.emptyList()); 284 | return; 285 | } 286 | 287 | List originalList = converter.read(file, type); 288 | if (originalList == null) originalList = Collections.emptyList(); 289 | 290 | int indexOfItemToReplace = -1; 291 | 292 | for (int i = 0; i < originalList.size(); i++) { 293 | if (predicateFunc.test(originalList.get(i))) { 294 | indexOfItemToReplace = i; 295 | break; 296 | } 297 | } 298 | 299 | List modifiedList = new ArrayList(originalList); 300 | 301 | if (indexOfItemToReplace != -1) { 302 | modifiedList.remove(indexOfItemToReplace); 303 | modifiedList.add(indexOfItemToReplace, value); 304 | converterWrite(modifiedList, converter, type, file); 305 | } 306 | 307 | emitter.onSuccess(modifiedList); 308 | updateSubject.onNext(modifiedList); 309 | } 310 | }); 311 | } 312 | }); 313 | } 314 | 315 | @Override public void replace(@NonNull T value, @NonNull PredicateFunc predicateFunc) { 316 | replace(value, Schedulers.io(), predicateFunc); 317 | } 318 | 319 | @Override public void replace(@NonNull T value, @NonNull Scheduler scheduler, 320 | @NonNull PredicateFunc predicateFunc) { 321 | assertNotNull(scheduler, "scheduler"); 322 | observeReplace(value, predicateFunc).subscribeOn(scheduler).subscribe(); 323 | } 324 | 325 | @Override @NonNull public Single> observeAddOrReplace(@NonNull final T value, 326 | @NonNull final PredicateFunc predicateFunc) { 327 | assertNotNull(value, "value"); 328 | assertNotNull(predicateFunc, "predicateFunc"); 329 | 330 | return Single.create(new SingleOnSubscribe>() { 331 | @Override public void subscribe(final SingleEmitter> emitter) throws Exception { 332 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 333 | @Override public void run() throws Exception { 334 | if (!file.exists() && !file.createNewFile()) { 335 | throw new IOException("Could not create store."); 336 | } 337 | 338 | List originalList = converter.read(file, type); 339 | if (originalList == null) originalList = Collections.emptyList(); 340 | 341 | int indexOfItemToReplace = -1; 342 | 343 | for (int i = 0; i < originalList.size(); i++) { 344 | if (predicateFunc.test(originalList.get(i))) { 345 | indexOfItemToReplace = i; 346 | break; 347 | } 348 | } 349 | 350 | int modifiedListSize = indexOfItemToReplace == -1 ? originalList.size() + 1 : 351 | originalList.size(); 352 | 353 | List modifiedList = new ArrayList(modifiedListSize); 354 | modifiedList.addAll(originalList); 355 | 356 | if (indexOfItemToReplace == -1) { 357 | modifiedList.add(value); 358 | } else { 359 | modifiedList.remove(indexOfItemToReplace); 360 | modifiedList.add(indexOfItemToReplace, value); 361 | } 362 | 363 | converterWrite(modifiedList, converter, type, file); 364 | emitter.onSuccess(modifiedList); 365 | updateSubject.onNext(modifiedList); 366 | } 367 | }); 368 | } 369 | }); 370 | } 371 | 372 | @Override public void addOrReplace(@NonNull T value, @NonNull PredicateFunc predicateFunc) { 373 | addOrReplace(value, Schedulers.io(), predicateFunc); 374 | } 375 | 376 | @Override public void addOrReplace(@NonNull T value, @NonNull Scheduler scheduler, 377 | @NonNull PredicateFunc predicateFunc) { 378 | assertNotNull(scheduler, "scheduler"); 379 | observeAddOrReplace(value, predicateFunc).subscribeOn(scheduler).subscribe(); 380 | } 381 | 382 | static final class ListType implements ParameterizedType { 383 | private final Type wrappedType; 384 | 385 | ListType(Type wrappedType) { 386 | this.wrappedType = wrappedType; 387 | } 388 | 389 | @Override public Type[] getActualTypeArguments() { 390 | return new Type[] {wrappedType}; 391 | } 392 | 393 | @Override public Type getOwnerType() { 394 | return null; 395 | } 396 | 397 | @Override public Type getRawType() { 398 | return List.class; 399 | } 400 | } 401 | } 402 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/RealValueStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | import io.reactivex.Completable; 20 | import io.reactivex.CompletableEmitter; 21 | import io.reactivex.CompletableOnSubscribe; 22 | import io.reactivex.Maybe; 23 | import io.reactivex.MaybeEmitter; 24 | import io.reactivex.MaybeOnSubscribe; 25 | import io.reactivex.Observable; 26 | import io.reactivex.Scheduler; 27 | import io.reactivex.Single; 28 | import io.reactivex.SingleEmitter; 29 | import io.reactivex.SingleOnSubscribe; 30 | import io.reactivex.annotations.NonNull; 31 | import io.reactivex.annotations.Nullable; 32 | import io.reactivex.functions.Function; 33 | import io.reactivex.schedulers.Schedulers; 34 | import io.reactivex.subjects.PublishSubject; 35 | import java.io.File; 36 | import java.io.IOException; 37 | import java.lang.reflect.Type; 38 | import java.util.concurrent.locks.ReentrantReadWriteLock; 39 | 40 | import static au.com.gridstone.rxstore.Utils.converterWrite; 41 | import static au.com.gridstone.rxstore.Utils.runInReadLock; 42 | import static au.com.gridstone.rxstore.Utils.runInWriteLock; 43 | import static au.com.gridstone.rxstore.Utils.assertNotNull; 44 | 45 | final class RealValueStore implements ValueStore { 46 | private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 47 | private final PublishSubject> updateSubject = PublishSubject.create(); 48 | 49 | private final File file; 50 | private final Converter converter; 51 | private final Type type; 52 | 53 | RealValueStore(@NonNull File file, @NonNull Converter converter, @NonNull Type type) { 54 | assertNotNull(file, "file"); 55 | assertNotNull(converter, "converter"); 56 | assertNotNull(type, "type"); 57 | this.file = file; 58 | this.converter = converter; 59 | this.type = type; 60 | } 61 | 62 | @Override @NonNull public Maybe get() { 63 | return Maybe.create(new MaybeOnSubscribe() { 64 | @Override public void subscribe(final MaybeEmitter emitter) throws Exception { 65 | runInReadLock(readWriteLock, new ThrowingRunnable() { 66 | @Override public void run() throws Exception { 67 | if (!file.exists()) { 68 | emitter.onComplete(); 69 | return; 70 | } 71 | 72 | T value = converter.read(file, type); 73 | if (value == null) emitter.onComplete(); 74 | emitter.onSuccess(value); 75 | } 76 | }); 77 | } 78 | }); 79 | } 80 | 81 | @Override @Nullable public T blockingGet() { 82 | return get().blockingGet(); 83 | } 84 | 85 | @Override @NonNull public Single observePut(@NonNull final T value) { 86 | assertNotNull(value, "value"); 87 | 88 | return Single.create(new SingleOnSubscribe() { 89 | @Override public void subscribe(final SingleEmitter emitter) throws Exception { 90 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 91 | @Override public void run() throws Exception { 92 | if (!file.exists() && !file.createNewFile()) { 93 | throw new IOException("Could not create file for store."); 94 | } 95 | 96 | converterWrite(value, converter, type, file); 97 | emitter.onSuccess(value); 98 | updateSubject.onNext(new ValueUpdate(value)); 99 | } 100 | }); 101 | } 102 | }); 103 | } 104 | 105 | @Override public void put(@NonNull T value) { 106 | put(value, Schedulers.io()); 107 | } 108 | 109 | @Override public void put(@NonNull T value, @NonNull Scheduler scheduler) { 110 | assertNotNull(scheduler, "scheduler"); 111 | observePut(value).subscribeOn(scheduler).subscribe(); 112 | } 113 | 114 | @Override @NonNull public Observable> observe() { 115 | Observable> startingValue = get() 116 | .map(new Function>() { 117 | @Override public ValueUpdate apply(T value) throws Exception { 118 | return new ValueUpdate(value); 119 | } 120 | }) 121 | .defaultIfEmpty(ValueUpdate.empty()) 122 | .toObservable(); 123 | 124 | return updateSubject.startWith(startingValue); 125 | } 126 | 127 | @Override @NonNull public Completable observeClear() { 128 | return Completable.create(new CompletableOnSubscribe() { 129 | @Override public void subscribe(final CompletableEmitter emitter) throws Exception { 130 | runInWriteLock(readWriteLock, new ThrowingRunnable() { 131 | @Override public void run() throws Exception { 132 | if (file.exists() && !file.delete()) { 133 | throw new IOException("Clear operation on store failed."); 134 | } else { 135 | emitter.onComplete(); 136 | } 137 | 138 | updateSubject.onNext(ValueUpdate.empty()); 139 | } 140 | }); 141 | } 142 | }); 143 | } 144 | 145 | @Override public void clear() { 146 | clear(Schedulers.io()); 147 | } 148 | 149 | @Override public void clear(@NonNull Scheduler scheduler) { 150 | assertNotNull(scheduler, "scheduler"); 151 | observeClear().subscribeOn(scheduler).subscribe(); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/RxStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | import io.reactivex.annotations.NonNull; 20 | import java.io.File; 21 | import java.lang.reflect.Type; 22 | 23 | /** 24 | * Facilitates the read and write of objects to and from disk using RxJava and observing changes 25 | * over time. 26 | *

27 | * To create a store for a single object use {@link #value(File, Converter, Type)}. 28 | *

29 | * For {@code Lists} of objects use {@link #list(File, Converter, Type)}. 30 | */ 31 | public class RxStore { 32 | private RxStore() { 33 | throw new AssertionError("No instances."); 34 | } 35 | 36 | /** 37 | * Create a new {@link ValueStore} that is capable of persisting a single object to disk. 38 | */ 39 | public static ValueStore value(@NonNull File file, @NonNull Converter converter, @NonNull 40 | Type type) { 41 | return new RealValueStore(file, converter, type); 42 | } 43 | 44 | /** 45 | * Create a new {@link ListStore} that is capable of persisting many objects to disk. 46 | */ 47 | public static ListStore list(@NonNull File file, @NonNull Converter converter, 48 | @NonNull Type type) { 49 | return new RealListStore(file, converter, type); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/ThrowingRunnable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | interface ThrowingRunnable { 20 | void run() throws Exception; 21 | } 22 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/Utils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | import java.io.File; 20 | import java.io.IOException; 21 | import java.lang.reflect.Type; 22 | import java.util.concurrent.locks.Lock; 23 | import java.util.concurrent.locks.ReentrantReadWriteLock; 24 | 25 | final class Utils { 26 | private Utils() { 27 | throw new AssertionError("No instances."); 28 | } 29 | 30 | static void assertNotNull(Object object, String name) { 31 | if (object == null) { 32 | throw new NullPointerException(name + "must not be null."); 33 | } 34 | } 35 | 36 | static void runInReadLock(ReentrantReadWriteLock readWriteLock, ThrowingRunnable runnable) { 37 | Lock readLock = readWriteLock.readLock(); 38 | readLock.lock(); 39 | 40 | try { 41 | runnable.run(); 42 | } catch (Exception e) { 43 | throw new RuntimeException(e); 44 | } finally { 45 | readLock.unlock(); 46 | } 47 | } 48 | 49 | static void runInWriteLock(ReentrantReadWriteLock readWriteLock, ThrowingRunnable runnable) { 50 | Lock readLock = readWriteLock.readLock(); 51 | int readCount = readWriteLock.getWriteHoldCount() == 0 ? readWriteLock.getReadHoldCount() : 0; 52 | 53 | for (int i = 0; i < readCount; i++) { 54 | readLock.unlock(); 55 | } 56 | 57 | Lock writeLock = readWriteLock.writeLock(); 58 | writeLock.lock(); 59 | 60 | try { 61 | runnable.run(); 62 | } catch (Exception e) { 63 | throw new RuntimeException(e); 64 | } finally { 65 | for (int i = 0; i < readCount; i++) { 66 | readLock.lock(); 67 | } 68 | writeLock.unlock(); 69 | } 70 | } 71 | 72 | static void converterWrite(T value, Converter converter, Type type, File file) 73 | throws IOException { 74 | File tmpFile = new File(file.getAbsolutePath() + ".tmp"); 75 | converter.write(value, type, tmpFile); 76 | 77 | if (!file.delete() || !tmpFile.renameTo(file)) { 78 | throw new IOException("Failed to write value to file."); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /rxstore/src/main/java/au/com/gridstone/rxstore/ValueStore.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore; 18 | 19 | import io.reactivex.Completable; 20 | import io.reactivex.Maybe; 21 | import io.reactivex.Observable; 22 | import io.reactivex.Scheduler; 23 | import io.reactivex.Single; 24 | import io.reactivex.annotations.NonNull; 25 | import io.reactivex.annotations.Nullable; 26 | import io.reactivex.schedulers.Schedulers; 27 | 28 | /** 29 | * Store a single object on disk. 30 | */ 31 | public interface ValueStore { 32 | /** 33 | * Retrieve the current value from this store using Rx. If this store has not had a value written 34 | * then the returned {@link Maybe} completes without a value. 35 | */ 36 | @NonNull Maybe get(); 37 | 38 | /** 39 | * Retrieve the current value from this store in a blocking manner. This may take time. If the 40 | * store has not yet had a value written then this method returns null. 41 | */ 42 | @Nullable T blockingGet(); 43 | 44 | /** 45 | * Write an object to this store and observe the operation. The value returned in the {@link 46 | * Single} is the value written to this store, making it useful for chaining. 47 | */ 48 | @NonNull Single observePut(@NonNull final T value); 49 | 50 | /** 51 | * Asynchronously write a value to this store. The write operation occurs on {@link 52 | * Schedulers#io()}. If you wish to specify the {@link Scheduler} then use {@link #put(Object, 53 | * Scheduler)}. 54 | */ 55 | void put(@NonNull T value); 56 | 57 | /** 58 | * Write a value to this store on a specified {@link Scheduler}. 59 | */ 60 | void put(@NonNull T value, @NonNull Scheduler scheduler); 61 | 62 | /** 63 | * Observe changes to the value in this store. {@code onNext(valueUpdate)} will be invoked 64 | * immediately with the current value upon subscription and subsequent changes thereafter. 65 | *

66 | * Values are wrapped inside of {@link ValueUpdate ValueUpdate} objects, as it's possible for a 67 | * store to hold no current value. If that's the case {@link ValueUpdate#empty update.empty} will 68 | * be true and {@link ValueUpdate#value update.value} will be null. 69 | */ 70 | @NonNull Observable> observe(); 71 | 72 | /** 73 | * Clear the value in this store and observe the operation. (Useful for chaining). 74 | */ 75 | @NonNull Completable observeClear(); 76 | 77 | /** 78 | * Asynchronously clear the value in this store. The clear operation occurs on {@link 79 | * Schedulers#io()}. If you wish to specify the {@link Scheduler} then use {@link 80 | * #clear(Scheduler)}. 81 | */ 82 | void clear(); 83 | 84 | /** 85 | * Clear the value from this store on a specified {@link Scheduler}. 86 | */ 87 | void clear(@NonNull Scheduler scheduler); 88 | 89 | /** 90 | * Wraps the current value in a {@link ValueStore}. This is useful as {@link ValueStore#observe()} 91 | * is unable to deliver null objects in {@code onNext()} to represent an empty state. To that end, 92 | * you may query {@link ValueUpdate#empty update.empty} to determine if the current value is empty 93 | * and whether or not {@link ValueUpdate#value update.value} is null. 94 | */ 95 | final class ValueUpdate { 96 | @Nullable public final T value; 97 | public final boolean empty; 98 | 99 | ValueUpdate(@Nullable T value) { 100 | this.value = value; 101 | this.empty = value == null; 102 | } 103 | 104 | @Override public boolean equals(Object obj) { 105 | if (this == obj) return true; 106 | if (!(obj instanceof ValueUpdate)) return false; 107 | 108 | ValueUpdate other = (ValueUpdate) obj; 109 | if (this.empty) return other.empty; 110 | return this.value.equals(other.value); 111 | } 112 | 113 | @Override public int hashCode() { 114 | int valueHash = value == null ? 0 : value.hashCode(); 115 | int emptyHash = empty ? 1 : 0; 116 | return 37 * (valueHash + emptyHash); 117 | } 118 | 119 | @SuppressWarnings("unchecked") // Empty instance needs no type as value is always null. 120 | private static final ValueUpdate EMPTY = new ValueUpdate(null); 121 | 122 | @SuppressWarnings("unchecked") 123 | static ValueUpdate empty() { 124 | return (ValueUpdate) EMPTY; 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /rxstore/src/test/kotlin/au/com/gridstone/rxstore/ListStoreTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore 18 | 19 | import com.google.common.truth.Truth.assertThat 20 | import io.reactivex.schedulers.Schedulers 21 | import org.junit.Rule 22 | import org.junit.Test 23 | import org.junit.rules.TemporaryFolder 24 | import java.util.concurrent.TimeUnit.SECONDS 25 | 26 | class ListStoreTest { 27 | @Rule @JvmField val tempDir = TemporaryFolder().apply { create() } 28 | 29 | private fun newTestStore(): ListStore = 30 | RxStore.list(tempDir.newFile(), TestData.converter, TestData::class.java) 31 | 32 | @Test fun getOnEmptyReturnsEmpty() { 33 | val store = newTestStore() 34 | assertThat(store.blockingGet()).isEmpty() 35 | } 36 | 37 | @Test fun addToEmptyList() { 38 | val store = newTestStore() 39 | val value = TestData("test", 1) 40 | store.add(value, Schedulers.trampoline()) 41 | assertThat(store.blockingGet()).containsExactly(value) 42 | } 43 | 44 | @Test fun addToExistingList() { 45 | val store = newTestStore() 46 | val list = listOf(TestData("1", 1), TestData("2", 2)) 47 | store.put(list, Schedulers.trampoline()) 48 | assertThat(store.blockingGet()).isEqualTo(list) 49 | 50 | val newValue = TestData("3", 3) 51 | store.add(newValue, Schedulers.trampoline()) 52 | assertThat(store.blockingGet()).isEqualTo(list.plus(newValue)) 53 | } 54 | 55 | @Test fun removeFromList() { 56 | val store = newTestStore() 57 | val list = listOf(TestData("1", 1), TestData("2", 2)) 58 | store.put(list, Schedulers.trampoline()) 59 | 60 | store.remove(TestData("1", 1), Schedulers.trampoline()) 61 | assertThat(store.blockingGet()).containsExactly(TestData("2", 2)) 62 | } 63 | 64 | @Test fun removeFromListWithPredicate_oneItemRemoved() { 65 | val store = newTestStore() 66 | val list = listOf(TestData("1", 1), TestData("2", 2)) 67 | store.put(list, Schedulers.trampoline()) 68 | 69 | store.remove(Schedulers.trampoline()) { it.integer == 1 } 70 | assertThat(store.blockingGet()).containsExactly(TestData("2", 2)) 71 | } 72 | 73 | @Test fun removeFromListWithPredicate_noItemRemoved() { 74 | val store = newTestStore() 75 | val list = listOf(TestData("1", 1), TestData("2", 2)) 76 | store.put(list, Schedulers.trampoline()) 77 | 78 | store.remove(Schedulers.trampoline()) { it.integer == 3 } 79 | assertThat(store.blockingGet()).isEqualTo(list) 80 | } 81 | 82 | @Test fun removeFromListByIndex() { 83 | val store = newTestStore() 84 | val list = listOf(TestData("1", 1), TestData("2", 2)) 85 | store.put(list, Schedulers.trampoline()) 86 | 87 | store.remove(0, Schedulers.trampoline()) 88 | assertThat(store.blockingGet()).containsExactly(TestData("2", 2)) 89 | } 90 | 91 | @Test fun replaceInList_itemReplaced() { 92 | val store = newTestStore() 93 | val list = listOf(TestData("1", 1), TestData("2", 2)) 94 | store.put(list, Schedulers.trampoline()) 95 | 96 | store.replace(TestData("3", 3), Schedulers.trampoline()) { it.integer == 2 } 97 | assertThat(store.blockingGet()).containsExactly(TestData("1", 1), TestData("3", 3)) 98 | } 99 | 100 | @Test fun replaceInList_noItemReplaced() { 101 | val store = newTestStore() 102 | val list = listOf(TestData("1", 1), TestData("2", 2)) 103 | store.put(list, Schedulers.trampoline()) 104 | 105 | store.replace(TestData("3", 3), Schedulers.trampoline()) { it.integer == 3 } 106 | assertThat(store.blockingGet()).isEqualTo(list) 107 | } 108 | 109 | @Test fun addOrReplace_itemAdded() { 110 | val store = newTestStore() 111 | val list = listOf(TestData("1", 1), TestData("2", 2)) 112 | store.put(list, Schedulers.trampoline()) 113 | 114 | store.addOrReplace(TestData("3", 3), Schedulers.trampoline()) { it.integer == 3 } 115 | assertThat(store.blockingGet()).isEqualTo(list.plus(TestData("3", 3))) 116 | } 117 | 118 | @Test fun addOrReplace_itemReplaced() { 119 | val store = newTestStore() 120 | val list = listOf(TestData("1", 1), TestData("2", 2)) 121 | store.put(list, Schedulers.trampoline()) 122 | 123 | store.addOrReplace(TestData("3", 3), Schedulers.trampoline()) { it.integer == 2 } 124 | assertThat(store.blockingGet()).containsExactly(TestData("1", 1), TestData("3", 3)) 125 | } 126 | 127 | @Test fun updatesToListTriggerObservable() { 128 | val store = newTestStore() 129 | val testObserver = store.observe().test() 130 | 131 | val list = listOf(TestData("1", 1), TestData("2", 2)) 132 | store.put(list, Schedulers.trampoline()) 133 | 134 | val newValue = TestData("3", 3) 135 | store.add(newValue, Schedulers.trampoline()) 136 | 137 | store.clear(Schedulers.trampoline()) 138 | 139 | testObserver.assertValues(emptyList(), 140 | list, 141 | list.plus(newValue), 142 | emptyList()) 143 | testObserver.assertNotComplete() 144 | } 145 | 146 | @Test fun observePutProducesItem() { 147 | val store = newTestStore() 148 | val list = listOf(TestData("1", 1), TestData("2", 2)) 149 | val producedList = store.observePut(list).timeout(1, SECONDS).blockingGet() 150 | assertThat(producedList).isEqualTo(list) 151 | } 152 | 153 | @Test fun observeAddProducesItem() { 154 | val store = newTestStore() 155 | val value = TestData("1", 1) 156 | val producedList = store.observeAdd(value).timeout(1, SECONDS).blockingGet() 157 | assertThat(producedList).containsExactly(value) 158 | } 159 | 160 | @Test fun observeReplaceProducesItem() { 161 | val store = newTestStore() 162 | val list = listOf(TestData("1", 1), TestData("2", 2)) 163 | store.put(list, Schedulers.trampoline()) 164 | 165 | val producedList = store.observeReplace(TestData("3", 3)) { it.integer == 2 } 166 | .timeout(1, SECONDS) 167 | .blockingGet() 168 | 169 | assertThat(producedList).containsExactly(TestData("1", 1), TestData("3", 3)) 170 | } 171 | 172 | @Test fun observeAddOrReplaceProducesItem() { 173 | val store = newTestStore() 174 | val list = listOf(TestData("1", 1), TestData("2", 2)) 175 | store.put(list, Schedulers.trampoline()) 176 | 177 | val producedList = store.observeAddOrReplace(TestData("3", 3)) { it.integer == 3 } 178 | .timeout(1, SECONDS) 179 | .blockingGet() 180 | 181 | assertThat(producedList).isEqualTo(list.plus(TestData("3", 3))) 182 | } 183 | 184 | @Test fun observeRemoveByValueProducesItem() { 185 | val store = newTestStore() 186 | val list = listOf(TestData("1", 1), TestData("2", 2)) 187 | store.put(list, Schedulers.trampoline()) 188 | 189 | val producedList = store.observeRemove(TestData("1", 1)) 190 | .timeout(1, SECONDS) 191 | .blockingGet() 192 | 193 | assertThat(producedList).containsExactly(TestData("2", 2)) 194 | } 195 | 196 | @Test fun observeRemoveByIndexProducesItem() { 197 | val store = newTestStore() 198 | val list = listOf(TestData("1", 1), TestData("2", 2)) 199 | store.put(list, Schedulers.trampoline()) 200 | 201 | val producedList = store.observeRemove(0) 202 | .timeout(1, SECONDS) 203 | .blockingGet() 204 | 205 | assertThat(producedList).containsExactly(TestData("2", 2)) 206 | } 207 | 208 | @Test fun observeRemoveByPredicateProducesItem() { 209 | val store = newTestStore() 210 | val list = listOf(TestData("1", 1), TestData("2", 2)) 211 | store.put(list, Schedulers.trampoline()) 212 | 213 | val producedList = store.observeRemove { it.integer == 1 } 214 | .timeout(1, SECONDS) 215 | .blockingGet() 216 | 217 | assertThat(producedList).containsExactly(TestData("2", 2)) 218 | } 219 | 220 | @Test fun observeClearProducesItem() { 221 | val store = newTestStore() 222 | val list = listOf(TestData("1", 1), TestData("2", 2)) 223 | store.put(list, Schedulers.trampoline()) 224 | 225 | val producedList = store.observeClear().timeout(1, SECONDS).blockingGet() 226 | assertThat(producedList).isEmpty() 227 | } 228 | } 229 | -------------------------------------------------------------------------------- /rxstore/src/test/kotlin/au/com/gridstone/rxstore/TestData.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore 18 | 19 | import java.io.File 20 | import java.lang.reflect.Type 21 | 22 | data class TestData(val string: String, val integer: Int) { 23 | override fun toString() = "$string,$integer" 24 | 25 | companion object { 26 | fun fromString(string: String): TestData { 27 | val splitString = string.split(",") 28 | return TestData(splitString[0], splitString[1].toInt()) 29 | } 30 | 31 | @Suppress("UNCHECKED_CAST") // Special converter just for testing. Casts will always work. 32 | val converter = object : Converter { 33 | override fun write(data: T?, type: Type, file: File) { 34 | when (data) { 35 | null -> file.writeText("") 36 | is TestData -> file.writeText(data.toString()) 37 | is List<*> -> { 38 | val list = data as List 39 | // Separate each TestData instance by a "~" character. 40 | val listAsText = list.map { it.toString() }.reduce { acc, item -> "$acc~$item" } 41 | file.writeText(listAsText) 42 | } 43 | } 44 | } 45 | 46 | override fun read(file: File, type: Type): T? { 47 | val storedString = file.readText() 48 | if (storedString.isBlank()) return null 49 | 50 | if (type is RealListStore.ListType) { 51 | // Stored string contains each TestData separated by a "~" character. 52 | val splitString = storedString.split("~") 53 | val list = splitString.map { TestData.fromString(it) } 54 | 55 | return list as T 56 | } else { 57 | return TestData.fromString(storedString) as T 58 | } 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /rxstore/src/test/kotlin/au/com/gridstone/rxstore/ValueStoreTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package au.com.gridstone.rxstore 18 | 19 | import au.com.gridstone.rxstore.ValueStore.ValueUpdate 20 | import com.google.common.truth.Truth.assertThat 21 | import io.reactivex.schedulers.Schedulers 22 | import org.junit.Rule 23 | import org.junit.Test 24 | import org.junit.rules.TemporaryFolder 25 | import java.util.concurrent.TimeUnit.SECONDS 26 | 27 | class ValueStoreTest { 28 | @Rule @JvmField val tempDir = TemporaryFolder().apply { create() } 29 | 30 | private fun newTestStore(): ValueStore = 31 | RxStore.value(tempDir.newFile(), TestData.converter, TestData::class.java) 32 | 33 | private fun TestData.asUpdate(): ValueStore.ValueUpdate = ValueUpdate(this) 34 | 35 | @Test fun putAndClear() { 36 | val store = newTestStore() 37 | val value = TestData("test", 1) 38 | store.put(value, Schedulers.trampoline()) 39 | assertThat(store.blockingGet()).isEqualTo(value) 40 | 41 | store.clear(Schedulers.trampoline()) 42 | assertThat(store.blockingGet()).isNull() 43 | } 44 | 45 | @Test fun getSucceedsWithValueAndCompletesWithout() { 46 | val store = newTestStore() 47 | 48 | store.get().test() 49 | .assertComplete() 50 | .assertNoValues() 51 | 52 | val value = TestData("test", 1) 53 | store.put(value, Schedulers.trampoline()) 54 | 55 | store.get().test() 56 | .assertComplete() 57 | .assertValue(value) 58 | } 59 | 60 | @Test fun blockingGetOnEmptyReturnsNull() { 61 | val store = newTestStore() 62 | assertThat(store.blockingGet()).isNull() 63 | } 64 | 65 | @Test fun updatesTriggerObservable() { 66 | val store = newTestStore() 67 | val value1 = TestData("test", 1) 68 | val value2 = TestData("test", 2) 69 | 70 | val testObserver = store.observe().test() 71 | 72 | store.put(value1, Schedulers.trampoline()) 73 | store.put(value2, Schedulers.trampoline()) 74 | store.clear(Schedulers.trampoline()) 75 | 76 | testObserver.assertValues(ValueUpdate.empty(), 77 | value1.asUpdate(), 78 | value2.asUpdate(), 79 | ValueUpdate.empty()) 80 | testObserver.assertNotComplete() 81 | } 82 | 83 | @Test fun observePutProducesItem() { 84 | val value = TestData("test", 1) 85 | val store = newTestStore() 86 | val producedValue = store.observePut(value).timeout(1, SECONDS).blockingGet() 87 | assertThat(producedValue).isEqualTo(value) 88 | } 89 | 90 | @Test fun observeClearCompletes() { 91 | val value = TestData("test", 1) 92 | val store = newTestStore() 93 | store.put(value, Schedulers.trampoline()) 94 | assertThat(store.blockingGet()).isEqualTo(value) 95 | 96 | val testObserver = store.observeClear().subscribeOn(Schedulers.trampoline()).test() 97 | testObserver.assertComplete() 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'java' 18 | 19 | sourceCompatibility = 1.8 20 | targetCompatibility = 1.8 21 | 22 | dependencies { 23 | implementation rootProject.ext.rxJava 24 | implementation project(':rxstore') 25 | implementation project(':converters:moshi-converter') 26 | } 27 | -------------------------------------------------------------------------------- /sample/src/main/java/com/example/rxstore/RxStoreExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2017 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.example.rxstore; 18 | 19 | import au.com.gridstone.rxstore.Converter; 20 | import au.com.gridstone.rxstore.ListStore; 21 | import au.com.gridstone.rxstore.RxStore; 22 | import au.com.gridstone.rxstore.ValueStore; 23 | import au.com.gridstone.rxstore.converters.MoshiConverter; 24 | import io.reactivex.schedulers.Schedulers; 25 | import java.io.File; 26 | import java.util.Arrays; 27 | import java.util.List; 28 | 29 | public final class RxStoreExample { 30 | // Simple model class for the purpose of demonstration. 31 | static class Person { 32 | final String name; 33 | final int age; 34 | 35 | Person(String name, int age) { 36 | this.name = name; 37 | this.age = age; 38 | } 39 | } 40 | 41 | public static void main(String[] args) { 42 | // For this example we'll use Moshi to persist our model objects to disk as JSON. 43 | Converter converter = new MoshiConverter(); 44 | ValueStore personStore = RxStore.value(new File("person"), converter, Person.class); 45 | ListStore peopleStore = RxStore.list(new File("people"), converter, Person.class); 46 | 47 | // We can subscribe for updates every time our personStore changes. 48 | personStore.observe() 49 | .filter(update -> !update.empty) // We might only want non-empty updates. 50 | .map(update -> update.value) // If updates are non-empty we can get a non-null Person. 51 | .subscribe(person -> { 52 | // Here we receive a new person every time the store updates. 53 | }); 54 | 55 | // We can do the same for our ListStore of many people. 56 | peopleStore.observe().subscribe(people -> { 57 | // Now we'll be informed every time our list of people updates. 58 | }); 59 | 60 | // Make some model objects to persist. 61 | Person sally = new Person("Sally Sample", 30); 62 | List manyPeople = Arrays.asList( 63 | new Person("Trevor Tester", 24), 64 | new Person("Edward Example", 61), 65 | new Person("Daphne Demonstration", 9) 66 | ); 67 | 68 | // Here we'll write one person to disk and observe the operation. 69 | personStore.observePut(sally).subscribe(person -> { 70 | // In the onSuccess callback we now have a persisted model object to work with. 71 | }); 72 | 73 | // Write many people to a ListStore. Rather than observe the operation this time we'll just fire 74 | // and forget. We specify the Scheduler as trampoline to keep it simple and synchronous. 75 | peopleStore.put(manyPeople, Schedulers.trampoline()); 76 | 77 | // We can add one person at a time to our ListStore if we like. 78 | peopleStore.add(sally, Schedulers.trampoline()); 79 | 80 | // Let's remove Edward from our ListStore and observe the operation. 81 | peopleStore.observeRemove(person -> person.name.contains("Edward")).subscribe(people -> { 82 | // Now we have a list of people without Edward. 83 | }); 84 | 85 | // If we don't need our data persisted anymore we can clear the files from disk. 86 | personStore.clear(Schedulers.trampoline()); 87 | peopleStore.clear(Schedulers.trampoline()); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) GRIDSTONE 2016 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | include ':rxstore' 18 | include ':rxstore-kotlin' 19 | include ':converters:gson-converter' 20 | include ':converters:jackson-converter' 21 | include ':converters:moshi-converter' 22 | include ':sample' 23 | --------------------------------------------------------------------------------