├── .gitignore ├── LICENSE.txt ├── README.md ├── build.gradle ├── gradle.properties ├── gradle ├── local.properties └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── rxquery ├── .gitignore ├── build.gradle ├── gradle.properties └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── rxquery │ │ └── RxQuery.java │ └── test │ └── java │ └── rxquery │ └── RxQueryTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | .idea 4 | .DS_Store 5 | /build 6 | *.iml 7 | *.psd 8 | /app/src/main/assets/crashlytics-build.properties -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Konstantin Mikheev sirstripy-at-gmail-com 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RxQuery 2 | 3 | RxQuery is a very simple (102 lines of code) library that adds RxJava functionality to your database layer. 4 | This library is not limited by any ORM or direct SQL access. You can use ANY database kind you wish. 5 | Queries in this library are not tied to tables, so you can can make multiple select statements and 6 | return complex results. 7 | 8 | ## Introduction 9 | 10 | The core of this library is an "updatable query" which returns an object of any query-specific result type. 11 | You can trigger updatable queries by mentioning a table during a transaction execution. 12 | 13 | All data modifications and query updates happen in a background thread, with automatic delivery 14 | to the foreground thread. RxQuery creates a lock for every query, so 15 | you will never get into a situation when your data has been changed by another 16 | thread during successive database reads inside of one query. 17 | 18 | An updatable query will run after a data change with some delay. This is done to handle a problem of overproducing observable, 19 | see [debounce](https://github.com/ReactiveX/RxJava/wiki/Backpressure#debounce-or-throttlewithtimeout) RxJava operator. 20 | You can set this delay manually depending on your application needs. 21 | 22 | You can also use immediate (not updatable) queries in the main thread with RxQuery to get benefits of database locking and 23 | reactive operators chaining. 24 | 25 | ## Example 26 | 27 | This is how to register an updatable query which will run every time a change in "messages" or "notes" tables happens: 28 | 29 | ``` java 30 | q.updatable(asList("notes", "messages"), new Func0() { 31 | @Override 32 | public String call() { 33 | // your data access methods here 34 | return "Hello, world!"; 35 | } 36 | }) 37 | .subscribe(new Action1() { 38 | @Override 39 | public void call(String queryResult) { 40 | Log.v("", queryResult); 41 | } 42 | }); 43 | ``` 44 | 45 | Output: 46 | 47 | ``` text 48 | 10:00 Hello, world! 49 | ``` 50 | 51 | This is an example of a data changing action. The action will be automatically called inside of a transaction 52 | depending on the RxQuery configuration (see below). The call states that the action can alter data in "users" and "messages" 53 | tables, so all `updatable`s that are subscribed to these tables will be automatically updated. 54 | 55 | ``` java 56 | q.execution(asList("users", "messages"), new Action0() { 57 | @Override 58 | public void call() { 59 | // some data change 60 | } 61 | }).subscribe(); 62 | ``` 63 | 64 | Output: 65 | 66 | ``` text 67 | 10:00 Hello, world! 68 | 10:05 Hello, world! 69 | ``` 70 | 71 | ## Best practices 72 | 73 | Make your queries return immutable objects. Immutable objects are safe to share across an application, especially if your 74 | application is multi-threaded. When you're passing an immutable object you can be sure that your copy of the object 75 | will never be changed. Use [AutoParcel](https://github.com/frankiesardo/auto-parcel) library, use 76 | [SolidList](https://github.com/konmik/solid). 77 | More on benefits of immutable objects you can read in the Joshua Bloch's "Effective Java" book and in the description of 78 | [AutoValue](https://github.com/google/auto/tree/master/value) library. 79 | 80 | Do not expose your database cursor or any other low-level data structure to the view layer of an application. 81 | At first, such objects are not immutable. Second, this breaks layers of logic. 82 | You can read about an effective way to architect your Android application here: 83 | [Architecting Android... The clean way?](http://fernandocejas.com/2014/09/03/architecting-android-the-clean-way/) 84 | 85 | The proper way to use this library is inside of a Presenter. 86 | (You're already using [Model-View-Presenter](http://konmik.github.io/introduction-to-model-view-presenter-on-android.html), isn't it?) 87 | Anyway, you can use the library without MVP, the entire library is is just three simple observables. 88 | 89 | The entire pipeline with MVP would look like this (in a pseudocode). 90 | 91 | Query some data from a database: 92 | 93 | ``` java 94 | View: 95 | getPresenter().querySomeData(); 96 | 97 | Presenter.querySomeData: 98 | q 99 | .immediate({ model.readFromDatabase() }) 100 | .subscribe({ getView().publishSomeData(data); }); 101 | 102 | Model.readFromDatabase: 103 | your sql / orm / etc calls 104 | return data 105 | ``` 106 | 107 | A data change: 108 | 109 | ``` java 110 | View: 111 | getPresenter().changeSomeData(data); 112 | 113 | Presenter.changeSomeData: 114 | q 115 | .execute(changedTableName, { model.changeSomeRows(data) }) 116 | .subscribe(); 117 | 118 | Model.changeSomeRows: 119 | insert / delete / update 120 | ``` 121 | 122 | An updatable: 123 | 124 | ``` java 125 | Presenter.onCreate: 126 | q 127 | .updatable(tableName, { model.readFromDatabase() }) 128 | .subscribe({ getView().publishSomeData(data) }); // this part depends on your MVP library: there 129 | // should be a method to delay onNext until a view becomes available. 130 | ``` 131 | 132 | ## Installation 133 | 134 | ``` groovy 135 | dependencies { 136 | compile 'info.android15.rxquery:rxquery:2.0.0' 137 | } 138 | ``` 139 | 140 | ## Initialization 141 | 142 | ``` java 143 | RxQuery q = new RxQuery( 144 | Schedulers.from(Executors.newSingleThreadExecutor(new ThreadFactory() { 145 | @Override 146 | public Thread newThread(@NonNull Runnable r) { 147 | return new Thread(r, "transactions"); 148 | } 149 | })), 150 | AndroidSchedulers.mainThread(), 151 | 150, 152 | new Action1() { 153 | @Override 154 | public void call(final Action0 action0) { 155 | database.callInTransaction(action0); 156 | } 157 | } 158 | ) 159 | ``` 160 | 161 | ## References 162 | 163 | * [RxJava](https://github.com/ReactiveX/RxJava) 164 | * [Solid](https://github.com/konmik/solid) 165 | * [AutoParcel](https://github.com/frankiesardo/auto-parcel) 166 | * [Nucleus](https://github.com/konmik/nucleus) 167 | * [SQLite multithreading best practices](http://stackoverflow.com/questions/2493331/what-are-the-best-practices-for-sqlite-on-android/3689883#3689883) 168 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | } 5 | dependencies { 6 | classpath 'com.android.tools.build:gradle:1.1.0' 7 | } 8 | } 9 | 10 | allprojects { 11 | repositories { 12 | jcenter() 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | VERSION_CODE=2 21 | VERSION_NAME=2.0.0 22 | GROUP=info.android15.rxquery 23 | 24 | POM_DESCRIPTION=RxQuery is a very simple library that adds RxJava functionality to your database layer. 25 | POM_URL=https://github.com/konmik/RxQuery 26 | POM_SCM_URL=https://github.com/konmik/RxQuery 27 | POM_SCM_CONNECTION=scm:git@github.com:konmik/RxQuery.git 28 | POM_SCM_DEV_CONNECTION=scm:git@github.com:konimk/RxQuery.git 29 | POM_LICENCE_NAME=MIT 30 | POM_LICENCE_URL=http://opensource.org/licenses/MIT 31 | POM_LICENCE_DIST=repo 32 | POM_DEVELOPER_ID=sirstripy 33 | POM_DEVELOPER_NAME=Konstantin Mikheev 34 | 35 | #RELEASE_REPOSITORY_URL=file://C:/Users/konmik/.m2/repository 36 | SNAPSHOT_REPOSITORY_URL=file://C:/Users/konmik/.m2/repository 37 | -------------------------------------------------------------------------------- /gradle/local.properties: -------------------------------------------------------------------------------- 1 | ## This file is automatically generated by Android Studio. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must *NOT* be checked into Version Control Systems, 5 | # as it contains information specific to your local configuration. 6 | # 7 | # Location of the SDK. This is only used by Gradle. 8 | # For customization when using a Version Control System, please read the 9 | # header note. 10 | #Sat Feb 28 01:27:08 MSK 2015 11 | sdk.dir=C\:\\MyPrograms\\android-sdk 12 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/konmik/RxQuery/2832019bbc5042eac4ddbdcc35f52752b32516ae/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Apr 10 15:27:10 PDT 2013 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.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 | -------------------------------------------------------------------------------- /rxquery/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /rxquery/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 22 5 | buildToolsVersion "22.0.1" 6 | 7 | defaultConfig { 8 | minSdkVersion 15 9 | targetSdkVersion 22 10 | } 11 | } 12 | 13 | configurations { 14 | compileJavadoc 15 | } 16 | 17 | dependencies { 18 | compile 'io.reactivex:rxjava:1.0.12' 19 | testCompile 'junit:junit:4.12' 20 | } 21 | 22 | android.libraryVariants.all { variant -> 23 | def name = variant.buildType.name 24 | if (name.equals(com.android.builder.core.BuilderConstants.DEBUG)) { 25 | return; // Skip debug builds. 26 | } 27 | def task = project.tasks.create "jar${name.capitalize()}", Jar 28 | task.dependsOn variant.javaCompile 29 | task.from variant.javaCompile.destinationDir 30 | artifacts.add('archives', task); 31 | } 32 | 33 | apply from: '../gradle/gradle-mvn-push.gradle' 34 | -------------------------------------------------------------------------------- /rxquery/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=RxQuery 2 | POM_ARTIFACT_ID=rxquery 3 | POM_PACKAGING=jar 4 | -------------------------------------------------------------------------------- /rxquery/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /rxquery/src/main/java/rxquery/RxQuery.java: -------------------------------------------------------------------------------- 1 | package rxquery; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | import rx.Observable; 6 | import rx.Scheduler; 7 | import rx.Subscriber; 8 | import rx.functions.Action0; 9 | import rx.functions.Action1; 10 | import rx.functions.Func0; 11 | import rx.functions.Func1; 12 | import rx.subjects.PublishSubject; 13 | 14 | import static java.util.Collections.singletonList; 15 | 16 | /** 17 | * A class that allows to execute queries with a thread lock, 18 | * registers updatable queries and notifies updatables with database change events. 19 | * All executions, notifications and updates occur on the background scheduler. 20 | * All results from the background scheduler will be delivered on the foreground scheduler. 21 | */ 22 | public final class RxQuery { 23 | private final Scheduler backgroundScheduler; 24 | private final Scheduler foregroundScheduler; 25 | private final Action1 executor; 26 | private final int debounceMs; 27 | 28 | private final PublishSubject updates = PublishSubject.create(); 29 | private final Object lock = new Object(); 30 | 31 | /** 32 | * @param backgroundScheduler a scheduler that will be used for background actions execution. 33 | * @param foregroundScheduler a scheduler that will be used for background actions result delivery. 34 | * @param debounceMs amount of time in milliseconds to wait after a matching 35 | * table change before updating an updatable. 36 | * See {@link #updatable}, {@link rx.Observable#debounce} 37 | * @param executor an executor for {@link #execution} calls. Use it to 38 | * supply transaction executor that is specific to the database api. 39 | */ 40 | public RxQuery(Scheduler backgroundScheduler, Scheduler foregroundScheduler, int debounceMs, Action1 executor) { 41 | this.backgroundScheduler = backgroundScheduler; 42 | this.foregroundScheduler = foregroundScheduler; 43 | this.debounceMs = debounceMs; 44 | this.executor = executor; 45 | } 46 | 47 | /** 48 | * Immediately executes a query on the current thread, performing a lock on the database. 49 | * 50 | * @param query a query to execute. 51 | * @param query result type. 52 | * @return an observable that will emit a query result. 53 | */ 54 | public Observable immediate(final Func0 query) { 55 | return Observable.create(new Observable.OnSubscribe() { 56 | @Override 57 | public void call(Subscriber subscriber) { 58 | R result; 59 | synchronized (lock) { 60 | result = query.call(); 61 | } 62 | subscriber.onNext(result); 63 | subscriber.onCompleted(); 64 | } 65 | }); 66 | } 67 | 68 | /** 69 | * Creates an observable that executes a given query in the current thread immediately and 70 | * re-executes the query on the background scheduler in case of a given tables change. 71 | * The reason why first query is immediate is that a user should not see an empty screen 72 | * in case if the screen transition is immediate. 73 | * 74 | * @param a type of returning data 75 | * @param tables a table list to observe for updates 76 | * @param query a query to execute and to use for data updates 77 | * @return an observable that returns query results 78 | */ 79 | public Observable updatable(final Iterable tables, final Func0 query) { 80 | return updates 81 | .filter(new Func1() { 82 | @Override 83 | public Boolean call(String it) { 84 | for (String table : tables) 85 | if (table.equals(it)) 86 | return Boolean.TRUE; 87 | return Boolean.FALSE; 88 | } 89 | }) 90 | .observeOn(backgroundScheduler) 91 | .debounce(debounceMs, TimeUnit.MILLISECONDS, backgroundScheduler) 92 | .map(new Func1() { 93 | @Override 94 | public R call(String s) { 95 | synchronized (lock) { 96 | return query.call(); 97 | } 98 | } 99 | }) 100 | .observeOn(foregroundScheduler) 101 | .startWith(new Func0() { 102 | @Override 103 | public R call() { 104 | synchronized (lock) { 105 | return query.call(); 106 | } 107 | } 108 | }.call()); 109 | } 110 | 111 | /** 112 | * A shortcut for {@link #updatable(Iterable, Func0)} with one table. 113 | */ 114 | public Observable updatable(String table, Func0 query) { 115 | return updatable(singletonList(table), query); 116 | } 117 | 118 | /** 119 | * Executes an action on a background scheduler. 120 | * Notifies all subscribed updatables with data changes on given tables. 121 | * 122 | * @param tables tables that may be changed by the execution. 123 | * @param action an action to execute. 124 | * @return an observable that needs to be subscribed to run the action 125 | */ 126 | public Observable execution(final Iterable tables, final Action0 action) { 127 | return Observable 128 | .create(new Observable.OnSubscribe() { 129 | @Override 130 | public void call(Subscriber subscriber) { 131 | synchronized (lock) { 132 | executor.call(action); 133 | } 134 | for (String table : tables) 135 | updates.onNext(table); 136 | subscriber.onCompleted(); 137 | } 138 | }) 139 | .subscribeOn(backgroundScheduler) 140 | .observeOn(foregroundScheduler); 141 | } 142 | 143 | /** 144 | * A shortcut for {@link #execution(Iterable, Action0)} with one table. 145 | */ 146 | public Observable execution(String table, Action0 action) { 147 | return execution(singletonList(table), action); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /rxquery/src/test/java/rxquery/RxQueryTest.java: -------------------------------------------------------------------------------- 1 | package rxquery; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import java.util.concurrent.TimeUnit; 6 | import java.util.concurrent.atomic.AtomicInteger; 7 | import java.util.concurrent.atomic.AtomicLong; 8 | 9 | import rx.Subscription; 10 | import rx.functions.Action0; 11 | import rx.functions.Action1; 12 | import rx.functions.Func0; 13 | import rx.schedulers.TestScheduler; 14 | 15 | public class RxQueryTest extends TestCase { 16 | 17 | public static final String QUERY_RESULT = "query_result"; 18 | 19 | public void testImmediate() throws Exception { 20 | TestScheduler background = new TestScheduler(); 21 | TestScheduler foreground = new TestScheduler(); 22 | Action1 executor = new Action1() { 23 | @Override 24 | public void call(Action0 action0) { 25 | action0.call(); 26 | } 27 | }; 28 | RxQuery q = new RxQuery(background, foreground, 200, executor); 29 | final AtomicLong queryThread = new AtomicLong(); 30 | final AtomicLong resultThread = new AtomicLong(); 31 | 32 | q.immediate(new Func0() { 33 | @Override 34 | public String call() { 35 | queryThread.set(Thread.currentThread().getId()); 36 | return QUERY_RESULT; 37 | } 38 | }).subscribe(new Action1() { 39 | @Override 40 | public void call(String s) { 41 | assertEquals(QUERY_RESULT, s); 42 | resultThread.set(Thread.currentThread().getId()); 43 | } 44 | }); 45 | 46 | assertTrue(resultThread.get() != 0); 47 | assertEquals(queryThread.get(), resultThread.get()); 48 | assertEquals(queryThread.get(), Thread.currentThread().getId()); 49 | } 50 | 51 | public void testUpdatable() throws Exception { 52 | TestScheduler background = new TestScheduler(); 53 | TestScheduler foreground = new TestScheduler(); 54 | Action1 executor = new Action1() { 55 | @Override 56 | public void call(Action0 action0) { 57 | action0.call(); 58 | } 59 | }; 60 | RxQuery q = new RxQuery(background, foreground, 200, executor); 61 | 62 | final AtomicInteger queryCounter = new AtomicInteger(); 63 | Subscription subscription1 = q.updatable("data", new Func0() { 64 | @Override 65 | public String call() { 66 | queryCounter.incrementAndGet(); 67 | return QUERY_RESULT; 68 | } 69 | }).subscribe(); 70 | 71 | foreground.advanceTimeBy(300, TimeUnit.MILLISECONDS); 72 | 73 | assertEquals(1, queryCounter.get()); 74 | 75 | final Action0 action0 = new Action0() { 76 | @Override 77 | public void call() { 78 | 79 | } 80 | }; 81 | Subscription subscription2 = q.execution("data", new Action0() { 82 | @Override 83 | public void call() { 84 | action0.call(); 85 | } 86 | }).subscribe(); 87 | 88 | background.advanceTimeBy(300, TimeUnit.MILLISECONDS); 89 | foreground.advanceTimeBy(300, TimeUnit.MILLISECONDS); 90 | 91 | assertEquals(2, queryCounter.get()); 92 | } 93 | 94 | public void testExecution() throws Exception { 95 | TestScheduler background = new TestScheduler(); 96 | TestScheduler foreground = new TestScheduler(); 97 | Action1 executor = new Action1() { 98 | @Override 99 | public void call(Action0 action0) { 100 | action0.call(); 101 | } 102 | }; 103 | RxQuery q = new RxQuery(background, foreground, 200, executor); 104 | 105 | final AtomicInteger queryCounter = new AtomicInteger(); 106 | final AtomicInteger executionCounter = new AtomicInteger(); 107 | 108 | q.updatable("data", new Func0() { 109 | @Override 110 | public String call() { 111 | queryCounter.incrementAndGet(); 112 | return QUERY_RESULT; 113 | } 114 | }).subscribe(); 115 | 116 | q.execution("data", new Action0() { 117 | @Override 118 | public void call() { 119 | executionCounter.incrementAndGet(); 120 | } 121 | }).subscribe(); 122 | 123 | background.advanceTimeBy(300, TimeUnit.MILLISECONDS); 124 | 125 | assertEquals(1, executionCounter.get()); 126 | assertEquals(2, queryCounter.get()); 127 | 128 | q.execution("da!!!!!!ta", new Action0() { 129 | @Override 130 | public void call() { 131 | executionCounter.incrementAndGet(); 132 | } 133 | }).subscribe(); 134 | 135 | background.advanceTimeBy(300, TimeUnit.MILLISECONDS); 136 | 137 | assertEquals(2, queryCounter.get()); 138 | } 139 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':rxquery' 2 | --------------------------------------------------------------------------------