├── .github ├── workflows │ ├── .java-version │ ├── gradle-wrapper.yaml │ ├── build.yaml │ └── release.yaml └── renovate.json5 ├── copper ├── gradle.properties ├── build.gradle └── src │ └── main │ └── java │ └── app │ └── cash │ └── copper │ └── Query.kt ├── copper-rx2 ├── gradle.properties ├── build.gradle └── src │ ├── androidTest │ └── java │ │ └── app │ │ └── cash │ │ └── copper │ │ └── rx2 │ │ ├── QueueScheduler.java │ │ ├── AsRowsTest.java │ │ ├── RxContentResolverTest.java │ │ └── OperatorTest.java │ └── main │ └── java │ └── app │ └── cash │ └── copper │ └── rx2 │ ├── QueryToListObservable.kt │ ├── QueryToOptionalObservable.kt │ ├── QueryToOneObservable.kt │ └── RxContentResolver.kt ├── copper-rx3 ├── gradle.properties ├── build.gradle └── src │ ├── androidTest │ └── java │ │ └── app │ │ └── cash │ │ └── copper │ │ └── rx3 │ │ ├── QueueScheduler.java │ │ ├── AsRowsTest.java │ │ ├── RxContentResolverTest.java │ │ └── OperatorTest.java │ └── main │ └── java │ └── app │ └── cash │ └── copper │ └── rx3 │ ├── QueryToListObservable.kt │ ├── QueryToOptionalObservable.kt │ ├── QueryToOneObservable.kt │ └── RxContentResolver.kt ├── copper-flow ├── gradle.properties ├── build.gradle └── src │ ├── androidTest │ └── java │ │ └── app │ │ └── cash │ │ └── copper │ │ └── flow │ │ ├── AsRowsTest.kt │ │ ├── FlowContentResolverTest.kt │ │ └── OperatorTest.kt │ └── main │ └── java │ └── app │ └── cash │ └── copper │ └── flow │ └── FlowContentResolver.kt ├── gradle ├── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties └── libs.versions.toml ├── .gitignore ├── settings.gradle ├── .editorconfig ├── copper-testing ├── build.gradle └── src │ └── main │ └── java │ └── app │ └── cash │ └── copper │ └── testing │ ├── NullQuery.kt │ ├── CursorAssert.kt │ ├── Employee.kt │ └── TestContentProvider.java ├── CHANGELOG.md ├── gradle.properties ├── RELEASING.md ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE.txt /.github/workflows/.java-version: -------------------------------------------------------------------------------- 1 | 25 2 | -------------------------------------------------------------------------------- /copper/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=copper 2 | POM_NAME=Copper 3 | -------------------------------------------------------------------------------- /copper-rx2/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=copper-rx2 2 | POM_NAME=Copper (RxJava 2) 3 | -------------------------------------------------------------------------------- /copper-rx3/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=copper-rx3 2 | POM_NAME=Copper (RxJava 3) 3 | -------------------------------------------------------------------------------- /copper-flow/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=copper-flow 2 | POM_NAME=Copper (Coroutines Flow) 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cashapp/copper/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ IDEA 2 | .idea 3 | *.iml 4 | 5 | # Gradle 6 | .gradle 7 | build 8 | local.properties 9 | /reports 10 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'copper-root' 2 | 3 | include ':copper' 4 | include ':copper-flow' 5 | include ':copper-rx2' 6 | include ':copper-rx3' 7 | include ':copper-testing' 8 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_size = 2 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.{kt,kts}] 11 | kotlin_imports_layout=ascii 12 | -------------------------------------------------------------------------------- /copper-testing/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'org.jetbrains.kotlin.android' 3 | 4 | dependencies { 5 | api project(':copper') 6 | api libs.assertk 7 | } 8 | 9 | android { 10 | namespace "app.cash.copper.testing" 11 | } 12 | -------------------------------------------------------------------------------- /copper-testing/src/main/java/app/cash/copper/testing/NullQuery.kt: -------------------------------------------------------------------------------- 1 | package app.cash.copper.testing 2 | 3 | import android.database.Cursor 4 | import app.cash.copper.Query 5 | 6 | object NullQuery : Query { 7 | override fun run(): Cursor? { 8 | return null 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /copper/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'org.jetbrains.kotlin.android' 3 | apply plugin: 'com.vanniktech.maven.publish' 4 | 5 | dependencies { 6 | api libs.androidx.annotation 7 | } 8 | 9 | android { 10 | namespace "app.cash.copper" 11 | } 12 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /.github/workflows/gradle-wrapper.yaml: -------------------------------------------------------------------------------- 1 | name: gradle-wrapper 2 | 3 | on: 4 | pull_request: 5 | paths: 6 | - 'gradlew' 7 | - 'gradlew.bat' 8 | - 'gradle/wrapper/' 9 | 10 | jobs: 11 | validate: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v6 15 | - uses: gradle/actions/wrapper-validation@v5 16 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [Unreleased] 4 | 5 | Changed: 6 | 7 | - In-development snapshots are now published to the Central Portal Snapshots repository at https://central.sonatype.com/repository/maven-snapshots/. 8 | 9 | 10 | ## [1.0.0] - 2020-08-17 11 | 12 | Initial release forked from SQLBrite. 13 | 14 | 15 | [Unreleased]: https://github.com/cashapp/copper/compare/1.0.0...HEAD 16 | [1.0.0]: https://github.com/cashapp/copper/releases/tag/1.0.0 17 | -------------------------------------------------------------------------------- /copper-rx2/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'org.jetbrains.kotlin.android' 3 | apply plugin: 'com.vanniktech.maven.publish' 4 | 5 | dependencies { 6 | api project(':copper') 7 | api libs.rxjava2 8 | api libs.androidx.annotation 9 | 10 | androidTestImplementation project(':copper-testing') 11 | androidTestImplementation libs.androidx.test.runner 12 | androidTestImplementation libs.assertk 13 | } 14 | 15 | android { 16 | namespace "app.cash.copper.rx2" 17 | 18 | defaultConfig { 19 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /copper-flow/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'org.jetbrains.kotlin.android' 3 | apply plugin: 'com.vanniktech.maven.publish' 4 | 5 | dependencies { 6 | api project(':copper') 7 | api libs.kotlinx.coroutines.core 8 | api libs.androidx.annotation 9 | 10 | androidTestImplementation project(':copper-testing') 11 | androidTestImplementation libs.androidx.test.runner 12 | androidTestImplementation libs.assertk 13 | androidTestImplementation libs.turbine 14 | } 15 | 16 | android { 17 | namespace "app.cash.copper.flow" 18 | 19 | defaultConfig { 20 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /copper-rx3/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'org.jetbrains.kotlin.android' 3 | apply plugin: 'com.vanniktech.maven.publish' 4 | 5 | dependencies { 6 | api project(':copper') 7 | api libs.rxjava3 8 | api libs.androidx.annotation 9 | 10 | androidTestImplementation project(':copper-testing') 11 | androidTestImplementation libs.androidx.test.runner 12 | androidTestImplementation libs.assertk 13 | } 14 | 15 | android { 16 | namespace "app.cash.copper.rx3" 17 | 18 | defaultConfig { 19 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 20 | } 21 | 22 | packaging { 23 | excludes += "META-INF/COPYRIGHT" 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [libraries] 2 | android-gradlePlugin = "com.android.tools.build:gradle:8.13.1" 3 | 4 | androidx-annotation = "androidx.annotation:annotation:1.9.1" 5 | androidx-test-runner = "androidx.test:runner:1.5.2" 6 | 7 | kotlin-gradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:2.2.21" 8 | 9 | rxjava2 = "io.reactivex.rxjava2:rxjava:2.2.21" 10 | rxjava3 = "io.reactivex.rxjava3:rxjava:3.1.12" 11 | 12 | kotlinx-coroutines-core = "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2" 13 | turbine = "app.cash.turbine:turbine:1.2.1" 14 | assertk = "com.willowtreeapps.assertk:assertk:0.28.1" 15 | dokkaGradlePlugin = "org.jetbrains.dokka:dokka-gradle-plugin:2.1.0" 16 | gradleMavenPublishPlugin = "com.vanniktech:gradle-maven-publish-plugin:0.35.0" 17 | -------------------------------------------------------------------------------- /.github/renovate.json5: -------------------------------------------------------------------------------- 1 | { 2 | $schema: 'https://docs.renovatebot.com/renovate-schema.json', 3 | extends: [ 4 | 'config:recommended', 5 | ], 6 | ignorePresets: [ 7 | // Ensure we get the latest version and are not pinned to old versions. 8 | 'workarounds:javaLTSVersions', 9 | ], 10 | customManagers: [ 11 | // Update .java-version file with the latest JDK version. 12 | { 13 | customType: 'regex', 14 | fileMatch: [ 15 | '\\.java-version$', 16 | ], 17 | matchStrings: [ 18 | '(?.*)\\n', 19 | ], 20 | datasourceTemplate: 'java-version', 21 | depNameTemplate: 'java', 22 | // Only write the major version. 23 | extractVersionTemplate: '^(?\\d+)', 24 | }, 25 | ], 26 | } 27 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | GROUP=app.cash.copper 2 | VERSION_NAME=1.1.0-SNAPSHOT 3 | 4 | mavenCentralPublishing=true 5 | mavenCentralAutomaticPublishing=true 6 | signAllPublications=true 7 | 8 | POM_DESCRIPTION=A content provider wrapper for reactive queries. 9 | 10 | POM_URL=http://github.com/cashapp/copper/ 11 | POM_SCM_URL=http://github.com/cashapp/copper/ 12 | POM_SCM_CONNECTION=scm:git:git://github.com/cashapp/copper.git 13 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/cashapp/copper.git 14 | 15 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 16 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 17 | POM_LICENCE_DIST=repo 18 | 19 | POM_DEVELOPER_ID=square 20 | POM_DEVELOPER_NAME=Square, Inc. 21 | 22 | android.useAndroidX=true 23 | android.enableJetifier=false 24 | 25 | android.defaults.buildfeatures.buildconfig=false 26 | android.defaults.buildfeatures.aidl=false 27 | android.defaults.buildfeatures.renderscript=false 28 | android.defaults.buildfeatures.resvalues=false 29 | android.defaults.buildfeatures.shaders=false 30 | 31 | org.gradle.jvmargs=-Xmx4096m 32 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | # Releasing 2 | 3 | 1. Update the `VERSION_NAME` in `gradle.properties` to the release version. 4 | 5 | 2. Update the `CHANGELOG.md`: 6 | 1. Change the `Unreleased` header to the release version. 7 | 2. Add a link URL to ensure the header link works. 8 | 3. Add a new `Unreleased` section to the top. 9 | 10 | 3. Update the `README.md` so the "Download" section reflects the new release version and the 11 | snapshot section reflects the next "SNAPSHOT" version. 12 | 13 | 4. Commit 14 | 15 | ``` 16 | $ git commit -am "Prepare version X.Y.X" 17 | ``` 18 | 19 | 5. Tag 20 | 21 | ``` 22 | $ git tag -am "Version X.Y.Z" X.Y.Z 23 | ``` 24 | 25 | 6. Update the `VERSION_NAME` in `gradle.properties` to the next "SNAPSHOT" version. 26 | 27 | 7. Commit 28 | 29 | ``` 30 | $ git commit -am "Prepare next development version" 31 | ``` 32 | 33 | 8. Push! 34 | 35 | ``` 36 | $ git push && git push --tags 37 | ``` 38 | 39 | This will trigger a GitHub Action workflow which will create a GitHub release and upload the 40 | release artifacts to Sonatype Nexus. 41 | 42 | 9. Visit [Sonatype Nexus](https://oss.sonatype.org/) and promote the artifact. 43 | -------------------------------------------------------------------------------- /copper-testing/src/main/java/app/cash/copper/testing/CursorAssert.kt: -------------------------------------------------------------------------------- 1 | package app.cash.copper.testing 2 | 3 | import android.database.Cursor 4 | import app.cash.copper.Query 5 | import assertk.assertThat 6 | import assertk.assertions.isEqualTo 7 | import assertk.assertions.isTrue 8 | 9 | class CursorAssert(private val cursor: Cursor) { 10 | private var row = 0 11 | 12 | fun hasRow(vararg values: Any?) = apply { 13 | assertThat(cursor.moveToNext(), name = "row ${row + 1} exists").isTrue() 14 | row += 1 15 | assertThat(cursor.columnCount, name = "column count").isEqualTo(values.size) 16 | for (i in values.indices) { 17 | assertThat(cursor.getString(i), name = "row $row column '${cursor.getColumnName(i)}'") 18 | .isEqualTo(values[i]) 19 | } 20 | } 21 | 22 | fun isExhausted() { 23 | if (cursor.moveToNext()) { 24 | val data = StringBuilder() 25 | for (i in 0 until cursor.columnCount) { 26 | if (i > 0) data.append(", ") 27 | data.append(cursor.getString(i)) 28 | } 29 | throw AssertionError("Expected no more rows but was: $data") 30 | } 31 | cursor.close() 32 | } 33 | } 34 | 35 | fun Query.assert(body: CursorAssert.() -> Unit) { 36 | CursorAssert(run()!!).apply(body).isExhausted() 37 | } 38 | -------------------------------------------------------------------------------- /.github/workflows/build.yaml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | pull_request: {} 5 | workflow_dispatch: {} 6 | push: 7 | branches: 8 | - 'trunk' 9 | tags-ignore: 10 | - '**' 11 | 12 | env: 13 | GRADLE_OPTS: "-Dorg.gradle.jvmargs=-Xmx4g -Dorg.gradle.daemon=false -Dkotlin.incremental=false" 14 | 15 | jobs: 16 | build: 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - name: Enable KVM group perms 21 | run: | 22 | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules 23 | sudo udevadm control --reload-rules 24 | sudo udevadm trigger --name-match=kvm 25 | 26 | - uses: actions/checkout@v6 27 | - uses: actions/setup-java@v5 28 | with: 29 | distribution: 'zulu' 30 | java-version-file: .github/workflows/.java-version 31 | 32 | - run: ./gradlew build assembleAndroidTest 33 | 34 | - name: Run Tests 35 | uses: reactivecircus/android-emulator-runner@v2 36 | with: 37 | api-level: 24 38 | script: ./gradlew connectedCheck 39 | 40 | - run: ./gradlew publish 41 | if: github.ref == 'refs/heads/trunk' 42 | env: 43 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_CENTRAL_USERNAME }} 44 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_CENTRAL_PASSWORD }} 45 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_SECRET_KEY }} 46 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.GPG_SECRET_PASSPHRASE }} 47 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | env: 9 | GRADLE_OPTS: "-Dorg.gradle.jvmargs=-Xmx4g -Dorg.gradle.daemon=false -Dkotlin.incremental=false" 10 | 11 | jobs: 12 | publish: 13 | runs-on: macOS-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v6 17 | - uses: actions/setup-java@v5 18 | with: 19 | distribution: 'zulu' 20 | java-version-file: .github/workflows/.java-version 21 | 22 | - run: ./gradlew build assembleAndroidTest 23 | 24 | - name: Run Tests 25 | uses: reactivecircus/android-emulator-runner@v2 26 | with: 27 | api-level: 24 28 | script: ./gradlew connectedCheck 29 | 30 | - name: Build and publish artifacts 31 | run: ./gradlew build publish 32 | env: 33 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_CENTRAL_USERNAME }} 34 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_CENTRAL_PASSWORD }} 35 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_SECRET_KEY }} 36 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.GPG_SECRET_PASSPHRASE }} 37 | 38 | github_release: 39 | runs-on: ubuntu-latest 40 | needs: 41 | - publish 42 | 43 | steps: 44 | - uses: actions/checkout@v6 45 | 46 | # Can only run on Linux. 47 | - name: Extract release notes 48 | id: release_notes 49 | uses: ffurrer2/extract-release-notes@v2 50 | 51 | - name: Create release 52 | uses: softprops/action-gh-release@v2 53 | with: 54 | body: ${{ steps.release_notes.outputs.release_notes }} 55 | env: 56 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 57 | -------------------------------------------------------------------------------- /copper-testing/src/main/java/app/cash/copper/testing/Employee.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | package app.cash.copper.testing 17 | 18 | import android.database.Cursor 19 | import android.database.MatrixCursor 20 | import app.cash.copper.Query 21 | 22 | data class Employee( 23 | @JvmField 24 | val username: String, 25 | @JvmField 26 | val name: String 27 | ) { 28 | companion object { 29 | private const val columnUsername = "username" 30 | private const val columnName = "name" 31 | 32 | @JvmStatic 33 | fun queryOf(vararg values: String): Query { 34 | return object : Query { 35 | override fun run(): Cursor? { 36 | val cursor = MatrixCursor(arrayOf(columnUsername, columnName)) 37 | for (i in values.indices step 2) { 38 | cursor.addRow(arrayOf(values[i], values[i + 1])) 39 | } 40 | return cursor 41 | } 42 | } 43 | } 44 | 45 | @JvmField 46 | val MAPPER: (Cursor) -> Employee = { cursor -> 47 | Employee( 48 | cursor.getString(cursor.getColumnIndexOrThrow(columnUsername)), 49 | cursor.getString(cursor.getColumnIndexOrThrow(columnName)) 50 | ) 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /copper-rx3/src/androidTest/java/app/cash/copper/rx3/QueueScheduler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Square, Inc. 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 | package app.cash.copper.rx3; 17 | 18 | import io.reactivex.rxjava3.annotations.NonNull; 19 | import io.reactivex.rxjava3.core.Scheduler; 20 | import io.reactivex.rxjava3.disposables.Disposable; 21 | import java.util.concurrent.BlockingDeque; 22 | import java.util.concurrent.LinkedBlockingDeque; 23 | import java.util.concurrent.TimeUnit; 24 | 25 | final class QueueScheduler extends Scheduler { 26 | private final BlockingDeque events = new LinkedBlockingDeque<>(); 27 | 28 | public Runnable awaitRunnable() throws InterruptedException { 29 | return events.pollFirst(5, TimeUnit.SECONDS); 30 | } 31 | 32 | @Override public Worker createWorker() { 33 | return new TestWorker(); 34 | } 35 | 36 | class TestWorker extends Worker { 37 | @Override 38 | public Disposable schedule(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) { 39 | events.add(run); 40 | return Disposable.fromRunnable(() -> events.remove(run)); 41 | } 42 | 43 | @Override public void dispose() { 44 | } 45 | 46 | @Override public boolean isDisposed() { 47 | return false; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /copper-rx2/src/androidTest/java/app/cash/copper/rx2/QueueScheduler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Square, Inc. 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 | package app.cash.copper.rx2; 17 | 18 | import io.reactivex.Scheduler; 19 | import io.reactivex.annotations.NonNull; 20 | import io.reactivex.disposables.Disposable; 21 | import io.reactivex.disposables.Disposables; 22 | import java.util.concurrent.BlockingDeque; 23 | import java.util.concurrent.LinkedBlockingDeque; 24 | import java.util.concurrent.TimeUnit; 25 | 26 | final class QueueScheduler extends Scheduler { 27 | private final BlockingDeque events = new LinkedBlockingDeque<>(); 28 | 29 | public Runnable awaitRunnable() throws InterruptedException { 30 | return events.pollFirst(5, TimeUnit.SECONDS); 31 | } 32 | 33 | @Override public Worker createWorker() { 34 | return new TestWorker(); 35 | } 36 | 37 | class TestWorker extends Worker { 38 | @Override 39 | public Disposable schedule(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) { 40 | events.add(run); 41 | return Disposables.fromRunnable(() -> events.remove(run)); 42 | } 43 | 44 | @Override public void dispose() { 45 | } 46 | 47 | @Override public boolean isDisposed() { 48 | return false; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /copper/src/main/java/app/cash/copper/Query.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | package app.cash.copper 17 | 18 | import android.content.ContentResolver 19 | import android.database.Cursor 20 | import android.net.Uri 21 | import androidx.annotation.CheckResult 22 | import androidx.annotation.WorkerThread 23 | 24 | /** An executable query. */ 25 | interface Query { 26 | /** 27 | * Execute the query on the underlying provider and return the resulting cursor. 28 | * 29 | * @return A [Cursor] with query results, or `null` when the query could not be 30 | * executed due to a problem with the underlying store. Unfortunately it is not well documented 31 | * when `null` is returned. It usually involves a problem in communicating with the 32 | * underlying store and should either be treated as failure or ignored for retry at a later 33 | * time. 34 | */ 35 | @CheckResult 36 | @WorkerThread 37 | fun run(): Cursor? 38 | } 39 | 40 | /** [Query] wrapper around [ContentResolver.query] */ 41 | class ContentResolverQuery( 42 | private val contentResolver: ContentResolver, 43 | private val uri: Uri, 44 | private val projection: Array?, 45 | private val selection: String?, 46 | private val selectionArgs: Array?, 47 | private val sortOrder: String? 48 | ) : Query { 49 | override fun run(): Cursor? { 50 | return contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /copper-flow/src/androidTest/java/app/cash/copper/flow/AsRowsTest.kt: -------------------------------------------------------------------------------- 1 | package app.cash.copper.flow 2 | 3 | import androidx.test.runner.AndroidJUnit4 4 | import app.cash.copper.testing.Employee 5 | import app.cash.copper.testing.Employee.Companion.queryOf 6 | import app.cash.copper.testing.NullQuery 7 | import app.cash.turbine.test 8 | import assertk.assertThat 9 | import assertk.assertions.isEqualTo 10 | import kotlin.time.ExperimentalTime 11 | import kotlinx.coroutines.ExperimentalCoroutinesApi 12 | import kotlinx.coroutines.flow.take 13 | import kotlinx.coroutines.runBlocking 14 | import org.junit.Test 15 | import org.junit.runner.RunWith 16 | 17 | @ExperimentalCoroutinesApi 18 | @ExperimentalTime 19 | @RunWith(AndroidJUnit4::class) 20 | class AsRowsTest { 21 | @Test fun asRowsEmpty() = runBlocking { 22 | queryOf() 23 | .asRows(mapper = Employee.MAPPER) 24 | .test { 25 | awaitComplete() 26 | } 27 | } 28 | 29 | @Test fun asRows() = runBlocking { 30 | queryOf("alice", "Alice Allison", "bob", "Bob Bobberson") 31 | .asRows(mapper = Employee.MAPPER) 32 | .test { 33 | assertThat(awaitItem()).isEqualTo(Employee("alice", "Alice Allison")) 34 | assertThat(awaitItem()).isEqualTo(Employee("bob", "Bob Bobberson")) 35 | awaitComplete() 36 | } 37 | } 38 | 39 | @Test fun asRowsStopsWhenCanceled() = runBlocking { 40 | var count = 0 41 | queryOf("alice", "Alice Allison", "bob", "Bob Bobberson", "eve", "Eve Evenson") 42 | .asRows { 43 | count++ 44 | Employee.MAPPER.invoke(it) 45 | } 46 | .take(1) 47 | .test { 48 | awaitItem() 49 | awaitComplete() 50 | } 51 | // This is 2 not 1 because of how the implementation works. It will always be N+1. 52 | assertThat(count).isEqualTo(2) 53 | } 54 | 55 | @Test fun asRowsEmptyWhenNullCursor() = runBlocking { 56 | var count = 0 57 | NullQuery 58 | .asRows { 59 | count++ 60 | Employee.MAPPER.invoke(it) 61 | } 62 | .test { 63 | awaitComplete() 64 | } 65 | assertThat(count).isEqualTo(0) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /copper-rx2/src/androidTest/java/app/cash/copper/rx2/AsRowsTest.java: -------------------------------------------------------------------------------- 1 | package app.cash.copper.rx2; 2 | 3 | import android.database.Cursor; 4 | import androidx.test.runner.AndroidJUnit4; 5 | import app.cash.copper.Query; 6 | import app.cash.copper.testing.Employee; 7 | import app.cash.copper.testing.NullQuery; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | import kotlin.jvm.functions.Function1; 10 | import org.junit.Test; 11 | import org.junit.runner.RunWith; 12 | 13 | import static app.cash.copper.testing.Employee.queryOf; 14 | import static org.junit.Assert.assertEquals; 15 | 16 | @RunWith(AndroidJUnit4.class) 17 | @SuppressWarnings("CheckResult") 18 | public final class AsRowsTest { 19 | @Test public void asRowsEmpty() { 20 | RxContentResolver.asRows(queryOf(), Employee.MAPPER) 21 | .test() 22 | .assertNoValues() 23 | .assertComplete(); 24 | } 25 | 26 | @Test public void asRows() { 27 | Query query = queryOf("alice", "Alice Allison", "bob", "Bob Bobberson"); 28 | RxContentResolver.asRows(query, Employee.MAPPER) 29 | .test() 30 | .assertValueAt(0, new Employee("alice", "Alice Allison")) 31 | .assertValueAt(1, new Employee("bob", "Bob Bobberson")) 32 | .assertComplete(); 33 | } 34 | 35 | @Test public void asRowsStopsWhenUnsubscribed() { 36 | final AtomicInteger count = new AtomicInteger(); 37 | Function1 mapper = c -> { 38 | count.incrementAndGet(); 39 | return Employee.MAPPER.invoke(c); 40 | }; 41 | 42 | Query query = queryOf("alice", "Alice Allison", "bob", "Bob Bobberson"); 43 | RxContentResolver.asRows(query, mapper) 44 | .take(1) 45 | .test() 46 | .assertValue(new Employee("alice", "Alice Allison")) 47 | .assertComplete(); 48 | assertEquals(1, count.get()); 49 | } 50 | 51 | @Test public void asRowsEmptyWhenNullCursor() { 52 | final AtomicInteger count = new AtomicInteger(); 53 | Function1 mapper = cursor -> { 54 | count.incrementAndGet(); 55 | return Employee.MAPPER.invoke(cursor); 56 | }; 57 | 58 | RxContentResolver.asRows(NullQuery.INSTANCE, mapper) 59 | .test() 60 | .assertNoValues() 61 | .assertComplete(); 62 | 63 | assertEquals(0, count.get()); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /copper-rx3/src/androidTest/java/app/cash/copper/rx3/AsRowsTest.java: -------------------------------------------------------------------------------- 1 | package app.cash.copper.rx3; 2 | 3 | import android.database.Cursor; 4 | import androidx.test.runner.AndroidJUnit4; 5 | import app.cash.copper.Query; 6 | import app.cash.copper.testing.Employee; 7 | import app.cash.copper.testing.NullQuery; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | import kotlin.jvm.functions.Function1; 10 | import org.junit.Test; 11 | import org.junit.runner.RunWith; 12 | 13 | import static app.cash.copper.testing.Employee.queryOf; 14 | import static org.junit.Assert.assertEquals; 15 | 16 | @RunWith(AndroidJUnit4.class) 17 | @SuppressWarnings("CheckResult") 18 | public final class AsRowsTest { 19 | @Test public void asRowsEmpty() { 20 | RxContentResolver.asRows(queryOf(), Employee.MAPPER) 21 | .test() 22 | .assertNoValues() 23 | .assertComplete(); 24 | } 25 | 26 | @Test public void asRows() { 27 | Query query = queryOf("alice", "Alice Allison", "bob", "Bob Bobberson"); 28 | RxContentResolver.asRows(query, Employee.MAPPER) 29 | .test() 30 | .assertValueAt(0, new Employee("alice", "Alice Allison")) 31 | .assertValueAt(1, new Employee("bob", "Bob Bobberson")) 32 | .assertComplete(); 33 | } 34 | 35 | @Test public void asRowsStopsWhenUnsubscribed() { 36 | final AtomicInteger count = new AtomicInteger(); 37 | Function1 mapper = c -> { 38 | count.incrementAndGet(); 39 | return Employee.MAPPER.invoke(c); 40 | }; 41 | 42 | Query query = queryOf("alice", "Alice Allison", "bob", "Bob Bobberson"); 43 | RxContentResolver.asRows(query, mapper) 44 | .take(1) 45 | .test() 46 | .assertValue(new Employee("alice", "Alice Allison")) 47 | .assertComplete(); 48 | assertEquals(1, count.get()); 49 | } 50 | 51 | @Test public void asRowsEmptyWhenNullCursor() { 52 | final AtomicInteger count = new AtomicInteger(); 53 | Function1 mapper = cursor -> { 54 | count.incrementAndGet(); 55 | return Employee.MAPPER.invoke(cursor); 56 | }; 57 | 58 | RxContentResolver.asRows(NullQuery.INSTANCE, mapper) 59 | .test() 60 | .assertNoValues() 61 | .assertComplete(); 62 | 63 | assertEquals(0, count.get()); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /copper-testing/src/main/java/app/cash/copper/testing/TestContentProvider.java: -------------------------------------------------------------------------------- 1 | package app.cash.copper.testing; 2 | 3 | import android.content.ContentResolver; 4 | import android.content.ContentValues; 5 | import android.database.Cursor; 6 | import android.database.MatrixCursor; 7 | import android.net.Uri; 8 | import android.test.mock.MockContentProvider; 9 | import java.util.LinkedHashMap; 10 | import java.util.Map; 11 | 12 | public final class TestContentProvider extends MockContentProvider { 13 | public static final Uri AUTHORITY = Uri.parse("content://test_authority"); 14 | public static final Uri TABLE = AUTHORITY.buildUpon().appendPath("test_table").build(); 15 | public static final String KEY = "test_key"; 16 | public static final String VALUE = "test_value"; 17 | 18 | public static ContentValues testValues(String key, String value) { 19 | ContentValues result = new ContentValues(); 20 | result.put(KEY, key); 21 | result.put(VALUE, value); 22 | return result; 23 | } 24 | 25 | private final Map storage = new LinkedHashMap<>(); 26 | 27 | private ContentResolver contentResolver; 28 | 29 | public void init(ContentResolver contentResolver) { 30 | this.contentResolver = contentResolver; 31 | } 32 | 33 | @Override public Uri insert(Uri uri, ContentValues values) { 34 | storage.put(values.getAsString(KEY), values.getAsString(VALUE)); 35 | contentResolver.notifyChange(uri, null); 36 | return Uri.parse(AUTHORITY + "/" + values.getAsString(KEY)); 37 | } 38 | 39 | @Override public int update(Uri uri, ContentValues values, String selection, 40 | String[] selectionArgs) { 41 | for (String key : storage.keySet()) { 42 | storage.put(key, values.getAsString(VALUE)); 43 | } 44 | contentResolver.notifyChange(uri, null); 45 | return storage.size(); 46 | } 47 | 48 | @Override public int delete(Uri uri, String selection, String[] selectionArgs) { 49 | int result = storage.size(); 50 | storage.clear(); 51 | contentResolver.notifyChange(uri, null); 52 | return result; 53 | } 54 | 55 | @Override public Cursor query(Uri uri, String[] projection, String selection, 56 | String[] selectionArgs, String sortOrder) { 57 | MatrixCursor result = new MatrixCursor(new String[] { KEY, VALUE }); 58 | for (Map.Entry entry : storage.entrySet()) { 59 | result.addRow(new Object[] { entry.getKey(), entry.getValue() }); 60 | } 61 | return result; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /copper-rx2/src/main/java/app/cash/copper/rx2/QueryToListObservable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 Square, Inc. 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 | package app.cash.copper.rx2 17 | 18 | import android.database.Cursor 19 | import app.cash.copper.Query 20 | import io.reactivex.Observable 21 | import io.reactivex.ObservableSource 22 | import io.reactivex.Observer 23 | import io.reactivex.exceptions.Exceptions 24 | import io.reactivex.observers.DisposableObserver 25 | import io.reactivex.plugins.RxJavaPlugins 26 | import java.util.ArrayList 27 | 28 | internal class QueryToListObservable( 29 | private val upstream: ObservableSource, 30 | private val mapper: (Cursor) -> T 31 | ) : Observable>() { 32 | override fun subscribeActual(observer: Observer>) { 33 | upstream.subscribe(MappingObserver(observer, mapper)) 34 | } 35 | 36 | private class MappingObserver( 37 | private val downstream: Observer>, 38 | private val mapper: (Cursor) -> T 39 | ) : DisposableObserver() { 40 | override fun onStart() { 41 | downstream.onSubscribe(this) 42 | } 43 | 44 | override fun onNext(query: Query) { 45 | try { 46 | val cursor = query.run() 47 | if (cursor == null || isDisposed) { 48 | return 49 | } 50 | val items = ArrayList(cursor.count) 51 | cursor.use { 52 | while (cursor.moveToNext()) { 53 | items.add(mapper(cursor)) 54 | } 55 | } 56 | if (!isDisposed) { 57 | downstream.onNext(items) 58 | } 59 | } catch (e: Throwable) { 60 | Exceptions.throwIfFatal(e) 61 | onError(e) 62 | } 63 | } 64 | 65 | override fun onComplete() { 66 | if (!isDisposed) { 67 | downstream.onComplete() 68 | } 69 | } 70 | 71 | override fun onError(e: Throwable) { 72 | if (isDisposed) { 73 | RxJavaPlugins.onError(e) 74 | } else { 75 | downstream.onError(e) 76 | } 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /copper-rx3/src/main/java/app/cash/copper/rx3/QueryToListObservable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 Square, Inc. 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 | package app.cash.copper.rx3 17 | 18 | import android.database.Cursor 19 | import app.cash.copper.Query 20 | import io.reactivex.rxjava3.core.Observable 21 | import io.reactivex.rxjava3.core.ObservableSource 22 | import io.reactivex.rxjava3.core.Observer 23 | import io.reactivex.rxjava3.exceptions.Exceptions 24 | import io.reactivex.rxjava3.observers.DisposableObserver 25 | import io.reactivex.rxjava3.plugins.RxJavaPlugins 26 | import java.util.ArrayList 27 | 28 | internal class QueryToListObservable( 29 | private val upstream: ObservableSource, 30 | private val mapper: (Cursor) -> T 31 | ) : Observable>() { 32 | override fun subscribeActual(observer: Observer>) { 33 | upstream.subscribe(MappingObserver(observer, mapper)) 34 | } 35 | 36 | private class MappingObserver( 37 | private val downstream: Observer>, 38 | private val mapper: (Cursor) -> T 39 | ) : DisposableObserver() { 40 | override fun onStart() { 41 | downstream.onSubscribe(this) 42 | } 43 | 44 | override fun onNext(query: Query) { 45 | try { 46 | val cursor = query.run() 47 | if (cursor == null || isDisposed) { 48 | return 49 | } 50 | val items = ArrayList(cursor.count) 51 | cursor.use { 52 | while (cursor.moveToNext()) { 53 | items.add(mapper(cursor)) 54 | } 55 | } 56 | if (!isDisposed) { 57 | downstream.onNext(items) 58 | } 59 | } catch (e: Throwable) { 60 | Exceptions.throwIfFatal(e) 61 | onError(e) 62 | } 63 | } 64 | 65 | override fun onComplete() { 66 | if (!isDisposed) { 67 | downstream.onComplete() 68 | } 69 | } 70 | 71 | override fun onError(e: Throwable) { 72 | if (isDisposed) { 73 | RxJavaPlugins.onError(e) 74 | } else { 75 | downstream.onError(e) 76 | } 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /copper-rx2/src/main/java/app/cash/copper/rx2/QueryToOptionalObservable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 Square, Inc. 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 | package app.cash.copper.rx2 17 | 18 | import android.database.Cursor 19 | import androidx.annotation.RequiresApi 20 | import app.cash.copper.Query 21 | import io.reactivex.Observable 22 | import io.reactivex.ObservableSource 23 | import io.reactivex.Observer 24 | import io.reactivex.exceptions.Exceptions 25 | import io.reactivex.observers.DisposableObserver 26 | import io.reactivex.plugins.RxJavaPlugins 27 | import java.util.Optional 28 | 29 | @RequiresApi(24) 30 | internal class QueryToOptionalObservable( 31 | private val upstream: ObservableSource, 32 | private val mapper: (Cursor) -> T 33 | ) : Observable>() { 34 | override fun subscribeActual(observer: Observer>) { 35 | upstream.subscribe(MappingObserver(observer, mapper)) 36 | } 37 | 38 | private class MappingObserver( 39 | private val downstream: Observer>, 40 | private val mapper: (Cursor) -> T 41 | ) : DisposableObserver() { 42 | override fun onStart() { 43 | downstream.onSubscribe(this) 44 | } 45 | 46 | override fun onNext(query: Query) { 47 | try { 48 | var item: T? = null 49 | query.run()?.use { cursor -> 50 | if (cursor.moveToNext()) { 51 | item = mapper(cursor) 52 | if (item == null) { 53 | downstream.onError(NullPointerException("QueryToOne mapper returned null")) 54 | return 55 | } 56 | check(!cursor.moveToNext()) { "Cursor returned more than 1 row" } 57 | } 58 | } 59 | if (!isDisposed) { 60 | downstream.onNext(Optional.ofNullable(item)) 61 | } 62 | } catch (e: Throwable) { 63 | Exceptions.throwIfFatal(e) 64 | onError(e) 65 | } 66 | } 67 | 68 | override fun onComplete() { 69 | if (!isDisposed) { 70 | downstream.onComplete() 71 | } 72 | } 73 | 74 | override fun onError(e: Throwable) { 75 | if (isDisposed) { 76 | RxJavaPlugins.onError(e) 77 | } else { 78 | downstream.onError(e) 79 | } 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /copper-rx3/src/main/java/app/cash/copper/rx3/QueryToOptionalObservable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 Square, Inc. 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 | package app.cash.copper.rx3 17 | 18 | import android.database.Cursor 19 | import androidx.annotation.RequiresApi 20 | import app.cash.copper.Query 21 | import io.reactivex.rxjava3.core.Observable 22 | import io.reactivex.rxjava3.core.ObservableSource 23 | import io.reactivex.rxjava3.core.Observer 24 | import io.reactivex.rxjava3.exceptions.Exceptions 25 | import io.reactivex.rxjava3.observers.DisposableObserver 26 | import io.reactivex.rxjava3.plugins.RxJavaPlugins 27 | import java.util.Optional 28 | 29 | @RequiresApi(24) 30 | internal class QueryToOptionalObservable( 31 | private val upstream: ObservableSource, 32 | private val mapper: (Cursor) -> T 33 | ) : Observable>() { 34 | override fun subscribeActual(observer: Observer>) { 35 | upstream.subscribe(MappingObserver(observer, mapper)) 36 | } 37 | 38 | private class MappingObserver( 39 | private val downstream: Observer>, 40 | private val mapper: (Cursor) -> T 41 | ) : DisposableObserver() { 42 | override fun onStart() { 43 | downstream.onSubscribe(this) 44 | } 45 | 46 | override fun onNext(query: Query) { 47 | try { 48 | var item: T? = null 49 | query.run()?.use { cursor -> 50 | if (cursor.moveToNext()) { 51 | item = mapper(cursor) 52 | if (item == null) { 53 | downstream.onError(NullPointerException("QueryToOne mapper returned null")) 54 | return 55 | } 56 | check(!cursor.moveToNext()) { "Cursor returned more than 1 row" } 57 | } 58 | } 59 | if (!isDisposed) { 60 | downstream.onNext(Optional.ofNullable(item)) 61 | } 62 | } catch (e: Throwable) { 63 | Exceptions.throwIfFatal(e) 64 | onError(e) 65 | } 66 | } 67 | 68 | override fun onComplete() { 69 | if (!isDisposed) { 70 | downstream.onComplete() 71 | } 72 | } 73 | 74 | override fun onError(e: Throwable) { 75 | if (isDisposed) { 76 | RxJavaPlugins.onError(e) 77 | } else { 78 | downstream.onError(e) 79 | } 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /copper-rx2/src/main/java/app/cash/copper/rx2/QueryToOneObservable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 Square, Inc. 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 | package app.cash.copper.rx2 17 | 18 | import android.database.Cursor 19 | import app.cash.copper.Query 20 | import io.reactivex.Observable 21 | import io.reactivex.ObservableSource 22 | import io.reactivex.Observer 23 | import io.reactivex.exceptions.Exceptions 24 | import io.reactivex.observers.DisposableObserver 25 | import io.reactivex.plugins.RxJavaPlugins 26 | 27 | internal class QueryToOneObservable( 28 | private val upstream: ObservableSource, 29 | private val mapper: (Cursor) -> T, 30 | /** A null `defaultValue` means nothing will be emitted when empty. */ 31 | private val defaultValue: T? 32 | ) : Observable() { 33 | override fun subscribeActual(observer: Observer) { 34 | upstream.subscribe(MappingObserver(observer, mapper, defaultValue)) 35 | } 36 | 37 | private class MappingObserver( 38 | private val downstream: Observer, 39 | private val mapper: (Cursor) -> T, 40 | private val defaultValue: T? 41 | ) : DisposableObserver() { 42 | override fun onStart() { 43 | downstream.onSubscribe(this) 44 | } 45 | 46 | override fun onNext(query: Query) { 47 | try { 48 | val item = query.run()?.use { cursor -> 49 | if (cursor.moveToNext()) { 50 | val item = mapper(cursor) 51 | if (item == null) { 52 | downstream.onError(NullPointerException("QueryToOne mapper returned null")) 53 | return 54 | } 55 | check(!cursor.moveToNext()) { "Cursor returned more than 1 row" } 56 | item 57 | } else { 58 | defaultValue 59 | } 60 | } 61 | if (item != null && !isDisposed) { 62 | downstream.onNext(item) 63 | } 64 | } catch (e: Throwable) { 65 | Exceptions.throwIfFatal(e) 66 | onError(e) 67 | } 68 | } 69 | 70 | override fun onComplete() { 71 | if (!isDisposed) { 72 | downstream.onComplete() 73 | } 74 | } 75 | 76 | override fun onError(e: Throwable) { 77 | if (isDisposed) { 78 | RxJavaPlugins.onError(e) 79 | } else { 80 | downstream.onError(e) 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /copper-rx3/src/main/java/app/cash/copper/rx3/QueryToOneObservable.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017 Square, Inc. 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 | package app.cash.copper.rx3 17 | 18 | import android.database.Cursor 19 | import app.cash.copper.Query 20 | import io.reactivex.rxjava3.core.Observable 21 | import io.reactivex.rxjava3.core.ObservableSource 22 | import io.reactivex.rxjava3.core.Observer 23 | import io.reactivex.rxjava3.exceptions.Exceptions 24 | import io.reactivex.rxjava3.observers.DisposableObserver 25 | import io.reactivex.rxjava3.plugins.RxJavaPlugins 26 | 27 | internal class QueryToOneObservable( 28 | private val upstream: ObservableSource, 29 | private val mapper: (Cursor) -> T, 30 | /** A null `defaultValue` means nothing will be emitted when empty. */ 31 | private val defaultValue: T? 32 | ) : Observable() { 33 | override fun subscribeActual(observer: Observer) { 34 | upstream.subscribe(MappingObserver(observer, mapper, defaultValue)) 35 | } 36 | 37 | private class MappingObserver( 38 | private val downstream: Observer, 39 | private val mapper: (Cursor) -> T, 40 | private val defaultValue: T? 41 | ) : DisposableObserver() { 42 | override fun onStart() { 43 | downstream.onSubscribe(this) 44 | } 45 | 46 | override fun onNext(query: Query) { 47 | try { 48 | val item = query.run()?.use { cursor -> 49 | if (cursor.moveToNext()) { 50 | val item = mapper(cursor) 51 | if (item == null) { 52 | downstream.onError(NullPointerException("QueryToOne mapper returned null")) 53 | return 54 | } 55 | check(!cursor.moveToNext()) { "Cursor returned more than 1 row" } 56 | item 57 | } else { 58 | defaultValue 59 | } 60 | } 61 | if (item != null && !isDisposed) { 62 | downstream.onNext(item) 63 | } 64 | } catch (e: Throwable) { 65 | Exceptions.throwIfFatal(e) 66 | onError(e) 67 | } 68 | } 69 | 70 | override fun onComplete() { 71 | if (!isDisposed) { 72 | downstream.onComplete() 73 | } 74 | } 75 | 76 | override fun onError(e: Throwable) { 77 | if (isDisposed) { 78 | RxJavaPlugins.onError(e) 79 | } else { 80 | downstream.onError(e) 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /copper-flow/src/androidTest/java/app/cash/copper/flow/FlowContentResolverTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | package app.cash.copper.flow 17 | 18 | import android.content.ContentResolver 19 | import android.test.ProviderTestCase2 20 | import app.cash.copper.testing.TestContentProvider 21 | import app.cash.copper.testing.TestContentProvider.AUTHORITY 22 | import app.cash.copper.testing.TestContentProvider.TABLE 23 | import app.cash.copper.testing.TestContentProvider.testValues 24 | import app.cash.copper.testing.assert 25 | import app.cash.turbine.test 26 | import kotlinx.coroutines.ExperimentalCoroutinesApi 27 | import kotlinx.coroutines.runBlocking 28 | import kotlin.time.ExperimentalTime 29 | 30 | @ExperimentalCoroutinesApi 31 | @ExperimentalTime 32 | class FlowContentResolverTest : ProviderTestCase2( 33 | TestContentProvider::class.java, AUTHORITY.authority 34 | ) { 35 | private lateinit var contentResolver: ContentResolver 36 | 37 | override fun setUp() { 38 | super.setUp() 39 | contentResolver = mockContentResolver 40 | provider.init(context.contentResolver) 41 | } 42 | 43 | fun testCreateQueryObservesInsert() = runBlocking { 44 | contentResolver.observeQuery(TABLE).test { 45 | awaitItem().assert { 46 | isExhausted() 47 | } 48 | 49 | contentResolver.insert(TABLE, testValues("key1", "val1")) 50 | awaitItem().assert { 51 | hasRow("key1", "val1") 52 | isExhausted() 53 | } 54 | 55 | cancel() 56 | } 57 | } 58 | 59 | fun testCreateQueryObservesUpdate() = runBlocking { 60 | contentResolver.insert(TABLE, testValues("key1", "val1")) 61 | 62 | contentResolver.observeQuery(TABLE).test { 63 | awaitItem().assert { 64 | hasRow("key1", "val1") 65 | isExhausted() 66 | } 67 | 68 | contentResolver.update(TABLE, testValues("key1", "val2"), null, null) 69 | awaitItem().assert { 70 | hasRow("key1", "val2") 71 | isExhausted() 72 | } 73 | 74 | cancel() 75 | } 76 | } 77 | 78 | fun testCreateQueryObservesDelete() = runBlocking { 79 | contentResolver.insert(TABLE, testValues("key1", "val1")) 80 | 81 | contentResolver.observeQuery(TABLE).test { 82 | awaitItem().assert { 83 | hasRow("key1", "val1") 84 | isExhausted() 85 | } 86 | 87 | contentResolver.delete(TABLE, null, null) 88 | awaitItem().assert { 89 | isExhausted() 90 | } 91 | 92 | cancel() 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | 74 | 75 | @rem Execute Gradle 76 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* 77 | 78 | :end 79 | @rem End local scope for the variables with windows NT shell 80 | if %ERRORLEVEL% equ 0 goto mainEnd 81 | 82 | :fail 83 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 84 | rem the _cmd.exe /c_ return code! 85 | set EXIT_CODE=%ERRORLEVEL% 86 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 87 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 88 | exit /b %EXIT_CODE% 89 | 90 | :mainEnd 91 | if "%OS%"=="Windows_NT" endlocal 92 | 93 | :omega 94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Copper 2 | 3 | A content provider wrapper for reactive queries with Kotlin coroutines `Flow` or 4 | RxJava `Observable`. 5 | 6 | ```kotlin 7 | contentResolver.observeQuery(uri).collect { query -> 8 | // ... 9 | } 10 | ``` 11 | 12 | 13 | ## Download 14 | 15 | ```groovy 16 | // Kotlin coroutines 17 | implementation 'app.cash.copper:copper-flow:1.0.0' 18 | 19 | // RxJava 3 20 | implementation 'app.cash.copper:copper-rx3:1.0.0' 21 | 22 | // RxJava 2 23 | implementation 'app.cash.copper:copper-rx2:1.0.0' 24 | ``` 25 | 26 |
27 | Snapshots of the development version are available in the Central Portal Snapshots repository. 28 |

29 | 30 | ```groovy 31 | repositories { 32 | maven { 33 | url 'https://central.sonatype.com/repository/maven-snapshots/' 34 | } 35 | } 36 | dependencies { 37 | testImplementation 'app.cash.copper:copper-flow:1.1.0-SNAPSHOT' 38 | testImplementation 'app.cash.copper:copper-rx2:1.1.0-SNAPSHOT' 39 | testImplementation 'app.cash.copper:copper-rx3:1.1.0-SNAPSHOT' 40 | } 41 | ``` 42 | 43 |

44 |
45 | 46 | 47 | ## Usage 48 | 49 | Given a [`ContentResolver`](https://developer.android.com/reference/android/content/ContentResolver), 50 | change your calls from `query` to `observeQuery` for a reactive version. 51 | 52 | ```kotlin 53 | contentResolver.observeQuery(uri).collect { query -> 54 | query.run()?.use { cursor -> 55 | // ... 56 | } 57 | } 58 | ``` 59 | 60 | Unlike `query`, `observeQuery` returns a `Query` object that you must call `run()` on in order to 61 | execute the underlying query for a `Cursor`. This ensures that intermediate operators which cache 62 | values do not leak resources and that consumers have access to the full lifetime of the cursor. 63 | 64 | Instead of dealing with a `Cursor` directly, operators are provided which help convert the 65 | contained values into semantic types: 66 | 67 | ```kotlin 68 | contentResolver.observeQuery(uri) 69 | .mapToOne { cursor -> 70 | Employee(cursor.getString(0), cursor.getString(1)) 71 | } 72 | .collect { 73 | println(it) 74 | } 75 | ``` 76 | ``` 77 | Employee(id=bob, name=Bob Bobberson) 78 | ``` 79 | 80 | The `mapToOne` operator takes a query which returns a single row and invokes the lambda to map the 81 | cursor to your desired type. If your query returns zero or one rows, the coroutine artifact has a 82 | `mapToOneOrNull` operator and the RxJava artifacts have a `mapToOptional` operator. 83 | 84 | If your query returns a list, call `mapToList` with the same lambda: 85 | 86 | ```kotlin 87 | contentResolver.observeQuery(uri) 88 | .mapToList { cursor -> 89 | Employee(cursor.getString(0), cursor.getString(1)) 90 | } 91 | .collect { 92 | println(it) 93 | } 94 | ``` 95 | ``` 96 | [Employee(id=alice, name=Alice Alison), Employee(id=bob, name=Bob Bobberson)] 97 | ``` 98 | 99 | 100 | # License 101 | 102 | Copyright 2015 Square, Inc. 103 | 104 | Licensed under the Apache License, Version 2.0 (the "License"); 105 | you may not use this file except in compliance with the License. 106 | You may obtain a copy of the License at 107 | 108 | http://www.apache.org/licenses/LICENSE-2.0 109 | 110 | Unless required by applicable law or agreed to in writing, software 111 | distributed under the License is distributed on an "AS IS" BASIS, 112 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 113 | See the License for the specific language governing permissions and 114 | limitations under the License. 115 | 116 | Note: This library was forked from [SQLBrite](https://github.com/square/sqlbrite). 117 | -------------------------------------------------------------------------------- /copper-rx2/src/androidTest/java/app/cash/copper/rx2/RxContentResolverTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | package app.cash.copper.rx2; 17 | 18 | import android.content.ContentResolver; 19 | import android.test.ProviderTestCase2; 20 | import app.cash.copper.Query; 21 | import app.cash.copper.testing.CursorAssert; 22 | import app.cash.copper.testing.TestContentProvider; 23 | import io.reactivex.observers.TestObserver; 24 | 25 | import static app.cash.copper.testing.TestContentProvider.AUTHORITY; 26 | import static app.cash.copper.testing.TestContentProvider.TABLE; 27 | import static app.cash.copper.testing.TestContentProvider.testValues; 28 | import static java.util.Objects.requireNonNull; 29 | 30 | public final class RxContentResolverTest extends ProviderTestCase2 { 31 | private ContentResolver contentResolver; 32 | 33 | public RxContentResolverTest() { 34 | super(TestContentProvider.class, AUTHORITY.getAuthority()); 35 | } 36 | 37 | @Override protected void setUp() throws Exception { 38 | super.setUp(); 39 | contentResolver = getMockContentResolver(); 40 | getProvider().init(getContext().getContentResolver()); 41 | } 42 | 43 | public void testCreateQueryObservesInsert() { 44 | TestObserver o = RxContentResolver.observeQuery(contentResolver, TABLE) 45 | .test(); 46 | assertCursor(o).isExhausted(); 47 | 48 | contentResolver.insert(TABLE, testValues("key1", "val1")); 49 | assertCursor(o).hasRow("key1", "val1").isExhausted(); 50 | 51 | o.dispose(); 52 | } 53 | 54 | public void testCreateQueryObservesUpdate() { 55 | contentResolver.insert(TABLE, testValues("key1", "val1")); 56 | 57 | TestObserver o = RxContentResolver.observeQuery(contentResolver, TABLE) 58 | .test(); 59 | assertCursor(o).hasRow("key1", "val1").isExhausted(); 60 | 61 | contentResolver.update(TABLE, testValues("key1", "val2"), null, null); 62 | assertCursor(o).hasRow("key1", "val2").isExhausted(); 63 | } 64 | 65 | public void testCreateQueryObservesDelete() { 66 | contentResolver.insert(TABLE, testValues("key1", "val1")); 67 | 68 | TestObserver o = RxContentResolver.observeQuery(contentResolver, TABLE) 69 | .test(); 70 | assertCursor(o).hasRow("key1", "val1").isExhausted(); 71 | 72 | contentResolver.delete(TABLE, null, null); 73 | assertCursor(o).isExhausted(); 74 | } 75 | 76 | public void testInitialValueAndTriggerUsesScheduler() throws InterruptedException { 77 | QueueScheduler scheduler = new QueueScheduler(); 78 | 79 | TestObserver o = 80 | RxContentResolver.observeQuery( 81 | contentResolver, TABLE, null, null, null, null, false, scheduler) 82 | .test(); 83 | o.assertValueCount(0); 84 | scheduler.awaitRunnable().run(); 85 | assertCursor(o).isExhausted(); 86 | 87 | contentResolver.insert(TABLE, testValues("key1", "val1")); 88 | o.assertValueCount(0); 89 | scheduler.awaitRunnable().run(); 90 | assertCursor(o).hasRow("key1", "val1").isExhausted(); 91 | } 92 | 93 | private static CursorAssert assertCursor(TestObserver o) { 94 | Query query = o.awaitCount(1).assertValueCount(1).values().remove(0); 95 | return new CursorAssert(requireNonNull(query.run())); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /copper-rx3/src/androidTest/java/app/cash/copper/rx3/RxContentResolverTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | package app.cash.copper.rx3; 17 | 18 | import android.content.ContentResolver; 19 | import android.test.ProviderTestCase2; 20 | import app.cash.copper.Query; 21 | import app.cash.copper.testing.CursorAssert; 22 | import app.cash.copper.testing.TestContentProvider; 23 | import io.reactivex.rxjava3.observers.TestObserver; 24 | 25 | import static app.cash.copper.testing.TestContentProvider.AUTHORITY; 26 | import static app.cash.copper.testing.TestContentProvider.TABLE; 27 | import static app.cash.copper.testing.TestContentProvider.testValues; 28 | import static java.util.Objects.requireNonNull; 29 | 30 | public final class RxContentResolverTest extends ProviderTestCase2 { 31 | private ContentResolver contentResolver; 32 | 33 | public RxContentResolverTest() { 34 | super(TestContentProvider.class, AUTHORITY.getAuthority()); 35 | } 36 | 37 | @Override protected void setUp() throws Exception { 38 | super.setUp(); 39 | contentResolver = getMockContentResolver(); 40 | getProvider().init(getContext().getContentResolver()); 41 | } 42 | 43 | public void testCreateQueryObservesInsert() { 44 | TestObserver o = RxContentResolver.observeQuery(contentResolver, TABLE) 45 | .test(); 46 | assertCursor(o).isExhausted(); 47 | 48 | contentResolver.insert(TABLE, testValues("key1", "val1")); 49 | assertCursor(o).hasRow("key1", "val1").isExhausted(); 50 | 51 | o.dispose(); 52 | } 53 | 54 | public void testCreateQueryObservesUpdate() { 55 | contentResolver.insert(TABLE, testValues("key1", "val1")); 56 | 57 | TestObserver o = RxContentResolver.observeQuery(contentResolver, TABLE) 58 | .test(); 59 | assertCursor(o).hasRow("key1", "val1").isExhausted(); 60 | 61 | contentResolver.update(TABLE, testValues("key1", "val2"), null, null); 62 | assertCursor(o).hasRow("key1", "val2").isExhausted(); 63 | } 64 | 65 | public void testCreateQueryObservesDelete() { 66 | contentResolver.insert(TABLE, testValues("key1", "val1")); 67 | 68 | TestObserver o = RxContentResolver.observeQuery(contentResolver, TABLE) 69 | .test(); 70 | assertCursor(o).hasRow("key1", "val1").isExhausted(); 71 | 72 | contentResolver.delete(TABLE, null, null); 73 | assertCursor(o).isExhausted(); 74 | } 75 | 76 | public void testInitialValueAndTriggerUsesScheduler() throws InterruptedException { 77 | QueueScheduler scheduler = new QueueScheduler(); 78 | 79 | TestObserver o = 80 | RxContentResolver.observeQuery( 81 | contentResolver, TABLE, null, null, null, null, false, scheduler) 82 | .test(); 83 | o.assertValueCount(0); 84 | scheduler.awaitRunnable().run(); 85 | assertCursor(o).isExhausted(); 86 | 87 | contentResolver.insert(TABLE, testValues("key1", "val1")); 88 | o.assertValueCount(0); 89 | scheduler.awaitRunnable().run(); 90 | assertCursor(o).hasRow("key1", "val1").isExhausted(); 91 | } 92 | 93 | private static CursorAssert assertCursor(TestObserver o) { 94 | Query query = o.awaitCount(1).assertValueCount(1).values().remove(0); 95 | return new CursorAssert(requireNonNull(query.run())); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /copper-flow/src/androidTest/java/app/cash/copper/flow/OperatorTest.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | package app.cash.copper.flow 17 | 18 | import android.database.Cursor 19 | import app.cash.copper.testing.Employee 20 | import app.cash.copper.testing.Employee.Companion.queryOf 21 | import app.cash.copper.testing.NullQuery 22 | import app.cash.turbine.test 23 | import assertk.assertThat 24 | import assertk.assertions.containsExactly 25 | import assertk.assertions.hasMessage 26 | import assertk.assertions.isEmpty 27 | import assertk.assertions.isEqualTo 28 | import assertk.assertions.isInstanceOf 29 | import kotlin.time.ExperimentalTime 30 | import kotlinx.coroutines.ExperimentalCoroutinesApi 31 | import kotlinx.coroutines.flow.flowOf 32 | import kotlinx.coroutines.runBlocking 33 | import org.junit.Test 34 | 35 | @ExperimentalCoroutinesApi 36 | @ExperimentalTime 37 | class OperatorTest { 38 | @Test fun mapToOne() = runBlocking { 39 | flowOf(queryOf("alice", "Alice Allison")) 40 | .mapToOne(mapper = Employee.MAPPER) 41 | .test { 42 | assertThat(awaitItem()).isEqualTo(Employee("alice", "Alice Allison")) 43 | awaitComplete() 44 | } 45 | } 46 | 47 | @Test fun mapToOneWithDefault() = runBlocking { 48 | flowOf(queryOf("alice", "Alice Allison")) 49 | .mapToOne(default = Employee("fred", "Fred Frederson"), mapper = Employee.MAPPER) 50 | .test { 51 | assertThat(awaitItem()).isEqualTo(Employee("alice", "Alice Allison")) 52 | awaitComplete() 53 | } 54 | } 55 | 56 | @Test fun mapToOneThrowsOnMultipleRows() = runBlocking { 57 | flowOf(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson")) 58 | .mapToOne(mapper = Employee.MAPPER) 59 | .test { 60 | assertThat(awaitError()) 61 | .isInstanceOf() 62 | .hasMessage("Cursor returned more than 1 row") 63 | } 64 | } 65 | 66 | @Test fun mapToOneEmptyIgnoredWithoutDefault() = runBlocking { 67 | flowOf(queryOf()) 68 | .mapToOne(mapper = Employee.MAPPER) 69 | .test { 70 | awaitComplete() 71 | } 72 | } 73 | 74 | @Test fun mapToOneWithDefaultEmpty() = runBlocking { 75 | flowOf(queryOf()) 76 | .mapToOne(default = Employee("fred", "Fred Frederson"), mapper = Employee.MAPPER) 77 | .test { 78 | assertThat(awaitItem()).isEqualTo(Employee("fred", "Fred Frederson")) 79 | awaitComplete() 80 | } 81 | } 82 | 83 | @Test fun mapToOneIgnoresNullCursor() = runBlocking { 84 | flowOf(NullQuery) 85 | .mapToOne(mapper = Employee.MAPPER) 86 | .test { 87 | awaitComplete() 88 | } 89 | } 90 | 91 | @Test fun mapToOneWithDefaultIgnoresNullCursor() = runBlocking { 92 | flowOf(NullQuery) 93 | .mapToOne(default = Employee("fred", "Fred Frederson"), mapper = Employee.MAPPER) 94 | .test { 95 | awaitComplete() 96 | } 97 | } 98 | 99 | @Test fun mapToList() = runBlocking { 100 | flowOf(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson", "eve", "Eve Evenson")) 101 | .mapToList(mapper = Employee.MAPPER) 102 | .test { 103 | assertThat(awaitItem()).containsExactly( 104 | Employee("alice", "Alice Allison"), 105 | Employee("bob", "Bob Bobberson"), 106 | Employee("eve", "Eve Evenson") 107 | ) 108 | awaitComplete() 109 | } 110 | } 111 | 112 | @Test fun mapToListEmptyWhenNoRows() = runBlocking { 113 | flowOf(queryOf()) 114 | .mapToList(mapper = Employee.MAPPER) 115 | .test { 116 | assertThat(awaitItem()).isEmpty() 117 | awaitComplete() 118 | } 119 | } 120 | 121 | @Test fun mapToListReturnsNullOnMapperNull() = runBlocking { 122 | val mapToNull = object : (Cursor) -> Employee? { 123 | private var count = 0 124 | 125 | override fun invoke(cursor: Cursor): Employee? { 126 | return if (count++ == 2) null else Employee.MAPPER.invoke(cursor) 127 | } 128 | } 129 | flowOf(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson", "eve", "Eve Evenson")) 130 | .mapToList(mapper = mapToNull) 131 | .test { 132 | assertThat(awaitItem()).containsExactly( 133 | Employee("alice", "Alice Allison"), 134 | Employee("bob", "Bob Bobberson"), 135 | null 136 | ) 137 | awaitComplete() 138 | } 139 | } 140 | 141 | @Test fun mapToListIgnoresNullCursor() = runBlocking { 142 | flowOf(NullQuery) 143 | .mapToList(mapper = Employee.MAPPER) 144 | .test { 145 | awaitComplete() 146 | } 147 | } 148 | 149 | @Test fun mapToOneOrNull() = runBlocking { 150 | flowOf(queryOf("alice", "Alice Allison")) 151 | .mapToOneOrNull(mapper = Employee.MAPPER) 152 | .test { 153 | assertThat(awaitItem()).isEqualTo(Employee("alice", "Alice Allison")) 154 | awaitComplete() 155 | } 156 | } 157 | 158 | @Test fun mapToOneOrNullThrowsOnMultipleRows() = runBlocking { 159 | flowOf(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson")) 160 | .mapToOneOrNull(mapper = Employee.MAPPER) 161 | .test { 162 | assertThat(awaitError()) 163 | .isInstanceOf() 164 | .hasMessage("Cursor returned more than 1 row") 165 | } 166 | } 167 | 168 | @Test fun mapToOneOrNullIgnoresNullCursor() = runBlocking { 169 | flowOf(NullQuery) 170 | .mapToOneOrNull(mapper = Employee.MAPPER) 171 | .test { 172 | awaitComplete() 173 | } 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /copper-rx2/src/androidTest/java/app/cash/copper/rx2/OperatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | package app.cash.copper.rx2; 17 | 18 | import android.database.Cursor; 19 | import androidx.test.filters.SdkSuppress; 20 | import app.cash.copper.testing.Employee; 21 | import app.cash.copper.testing.NullQuery; 22 | import java.util.Optional; 23 | import kotlin.jvm.functions.Function1; 24 | import org.junit.Test; 25 | 26 | import static app.cash.copper.testing.Employee.queryOf; 27 | import static io.reactivex.Observable.just; 28 | import static java.util.Arrays.asList; 29 | import static java.util.Collections.emptyList; 30 | 31 | public final class OperatorTest { 32 | @Test public void mapToOne() { 33 | just(queryOf("alice", "Alice Allison")) 34 | .to(o -> RxContentResolver.mapToOne(o, Employee.MAPPER)) 35 | .test() 36 | .assertValue(new Employee("alice", "Alice Allison")); 37 | } 38 | 39 | @Test public void mapToOneThrowsWhenMapperReturnsNull() { 40 | just(queryOf("alice", "Alice Allison")) 41 | .to(o -> RxContentResolver.mapToOne(o, c -> null)) 42 | .test() 43 | .assertError(NullPointerException.class) 44 | .assertErrorMessage("QueryToOne mapper returned null"); 45 | } 46 | 47 | @Test public void mapToOneWithDefault() { 48 | just(queryOf("alice", "Alice Allison")) 49 | .to(o -> RxContentResolver.mapToOne(o, new Employee("fred", "Fred Frederson"), Employee.MAPPER)) 50 | .test() 51 | .assertValue(new Employee("alice", "Alice Allison")); 52 | } 53 | 54 | @Test public void mapToOneThrowsOnMultipleRows() { 55 | just(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson")) 56 | .to(o -> RxContentResolver.mapToOne(o, Employee.MAPPER)) 57 | .test() 58 | .assertError(IllegalStateException.class) 59 | .assertErrorMessage("Cursor returned more than 1 row"); 60 | } 61 | 62 | @Test public void mapToOneEmptyIgnoredWithoutDefault() { 63 | just(queryOf()) 64 | .to(o -> RxContentResolver.mapToOne(o, Employee.MAPPER)) 65 | .test() 66 | .assertNoValues() 67 | .assertComplete(); 68 | } 69 | 70 | @Test public void mapToOneWithDefaultEmpty() { 71 | Employee defaultValue = new Employee("fred", "Fred Frederson"); 72 | just(queryOf()) 73 | .to(o -> RxContentResolver.mapToOne(o, defaultValue, Employee.MAPPER)) 74 | .test() 75 | .assertValue(defaultValue) 76 | .assertComplete(); 77 | } 78 | 79 | @Test public void mapToOneIgnoresNullCursor() { 80 | just(NullQuery.INSTANCE) 81 | .to(o -> RxContentResolver.mapToOne(o, Employee.MAPPER)) 82 | .test() 83 | .assertNoValues() 84 | .assertComplete(); 85 | } 86 | 87 | @Test public void mapToOneWithDefaultIgnoresNullCursor() { 88 | just(NullQuery.INSTANCE) 89 | .to(o -> RxContentResolver.mapToOne(o, new Employee("fred", "Fred Frederson"), Employee.MAPPER)) 90 | .test() 91 | .assertNoValues() 92 | .assertComplete(); 93 | } 94 | 95 | @Test public void mapToList() { 96 | just(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson", "eve", "Eve Evenson")) 97 | .to(o -> RxContentResolver.mapToList(o, Employee.MAPPER)) 98 | .test() 99 | .assertValue(asList( 100 | new Employee("alice", "Alice Allison"), // 101 | new Employee("bob", "Bob Bobberson"), // 102 | new Employee("eve", "Eve Evenson"))) 103 | .assertComplete(); 104 | } 105 | 106 | @Test public void mapToListEmptyWhenNoRows() { 107 | just(queryOf()) 108 | .to(o -> RxContentResolver.mapToList(o, Employee.MAPPER)) 109 | .test() 110 | .assertValue(emptyList()) 111 | .assertComplete(); 112 | } 113 | 114 | @Test public void mapToListReturnsNullOnMapperNull() { 115 | Function1 mapToNull = new Function1() { 116 | private int count; 117 | 118 | @Override public Employee invoke(Cursor cursor) { 119 | return count++ == 2 ? null : Employee.MAPPER.invoke(cursor); 120 | } 121 | }; 122 | just(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson", "eve", "Eve Evenson")) 123 | .to(o -> RxContentResolver.mapToList(o, mapToNull)) // 124 | .test() 125 | .assertValue(asList( 126 | new Employee("alice", "Alice Allison"), 127 | new Employee("bob", "Bob Bobberson"), 128 | null)) 129 | .assertComplete(); 130 | } 131 | 132 | @Test public void mapToListIgnoresNullCursor() { 133 | just(NullQuery.INSTANCE) 134 | .to(o -> RxContentResolver.mapToList(o, Employee.MAPPER)) 135 | .test() 136 | .assertNoValues() 137 | .assertComplete(); 138 | } 139 | 140 | @SdkSuppress(minSdkVersion = 24) 141 | @Test public void mapToOptional() { 142 | just(queryOf("alice", "Alice Allison")) 143 | .to(o -> RxContentResolver.mapToOptional(o, Employee.MAPPER)) 144 | .test() 145 | .assertValue(Optional.of(new Employee("alice", "Alice Allison"))); 146 | } 147 | 148 | @SdkSuppress(minSdkVersion = 24) 149 | @Test public void mapToOptionalThrowsWhenMapperReturnsNull() { 150 | just(queryOf("alice", "Alice Allison")) 151 | .to(o -> RxContentResolver.mapToOptional(o, c -> null)) 152 | .test() 153 | .assertError(NullPointerException.class) 154 | .assertErrorMessage("QueryToOne mapper returned null"); 155 | } 156 | 157 | @SdkSuppress(minSdkVersion = 24) 158 | @Test public void mapToOptionalThrowsOnMultipleRows() { 159 | just(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson")) 160 | .to(o -> RxContentResolver.mapToOptional(o, Employee.MAPPER)) 161 | .test() 162 | .assertError(IllegalStateException.class) 163 | .assertErrorMessage("Cursor returned more than 1 row"); 164 | } 165 | 166 | @SdkSuppress(minSdkVersion = 24) 167 | @Test public void mapToOptionalIgnoresNullCursor() { 168 | just(NullQuery.INSTANCE) 169 | .to(o -> RxContentResolver.mapToOptional(o, Employee.MAPPER)) 170 | .test() 171 | .assertValue(Optional.empty()); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /copper-rx3/src/androidTest/java/app/cash/copper/rx3/OperatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | package app.cash.copper.rx3; 17 | 18 | import android.database.Cursor; 19 | import androidx.test.filters.SdkSuppress; 20 | import app.cash.copper.testing.Employee; 21 | import app.cash.copper.testing.NullQuery; 22 | import java.util.Optional; 23 | import kotlin.jvm.functions.Function1; 24 | import org.junit.Test; 25 | 26 | import static app.cash.copper.testing.Employee.queryOf; 27 | import static io.reactivex.rxjava3.core.Observable.just; 28 | import static java.util.Arrays.asList; 29 | import static java.util.Collections.emptyList; 30 | 31 | public final class OperatorTest { 32 | @Test public void mapToOne() { 33 | just(queryOf("alice", "Alice Allison")) 34 | .to(o -> RxContentResolver.mapToOne(o, Employee.MAPPER)) 35 | .test() 36 | .assertValue(new Employee("alice", "Alice Allison")); 37 | } 38 | 39 | @Test public void mapToOneThrowsWhenMapperReturnsNull() { 40 | just(queryOf("alice", "Alice Allison")) 41 | .to(o -> RxContentResolver.mapToOne(o, c -> null)) 42 | .test() 43 | .assertError(t -> { 44 | return t instanceof NullPointerException 45 | && t.getMessage().equals("QueryToOne mapper returned null"); 46 | }); 47 | } 48 | 49 | @Test public void mapToOneWithDefault() { 50 | just(queryOf("alice", "Alice Allison")) 51 | .to(o -> RxContentResolver.mapToOne(o, new Employee("fred", "Fred Frederson"), Employee.MAPPER)) 52 | .test() 53 | .assertValue(new Employee("alice", "Alice Allison")); 54 | } 55 | 56 | @Test public void mapToOneThrowsOnMultipleRows() { 57 | just(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson")) 58 | .to(o -> RxContentResolver.mapToOne(o, Employee.MAPPER)) 59 | .test() 60 | .assertError(t -> { 61 | return t instanceof IllegalStateException 62 | && t.getMessage().equals("Cursor returned more than 1 row"); 63 | }); 64 | } 65 | 66 | @Test public void mapToOneEmptyIgnoredWithoutDefault() { 67 | just(queryOf()) 68 | .to(o -> RxContentResolver.mapToOne(o, Employee.MAPPER)) 69 | .test() 70 | .assertNoValues() 71 | .assertComplete(); 72 | } 73 | 74 | @Test public void mapToOneWithDefaultEmpty() { 75 | Employee defaultValue = new Employee("fred", "Fred Frederson"); 76 | just(queryOf()) 77 | .to(o -> RxContentResolver.mapToOne(o, defaultValue, Employee.MAPPER)) 78 | .test() 79 | .assertValue(defaultValue) 80 | .assertComplete(); 81 | } 82 | 83 | @Test public void mapToOneIgnoresNullCursor() { 84 | just(NullQuery.INSTANCE) 85 | .to(o -> RxContentResolver.mapToOne(o, Employee.MAPPER)) 86 | .test() 87 | .assertNoValues() 88 | .assertComplete(); 89 | } 90 | 91 | @Test public void mapToOneWithDefaultIgnoresNullCursor() { 92 | just(NullQuery.INSTANCE) 93 | .to(o -> RxContentResolver.mapToOne(o, new Employee("fred", "Fred Frederson"), Employee.MAPPER)) 94 | .test() 95 | .assertNoValues() 96 | .assertComplete(); 97 | } 98 | 99 | @Test public void mapToList() { 100 | just(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson", "eve", "Eve Evenson")) 101 | .to(o -> RxContentResolver.mapToList(o, Employee.MAPPER)) 102 | .test() 103 | .assertValue(asList( 104 | new Employee("alice", "Alice Allison"), // 105 | new Employee("bob", "Bob Bobberson"), // 106 | new Employee("eve", "Eve Evenson"))) 107 | .assertComplete(); 108 | } 109 | 110 | @Test public void mapToListEmptyWhenNoRows() { 111 | just(queryOf()) 112 | .to(o -> RxContentResolver.mapToList(o, Employee.MAPPER)) 113 | .test() 114 | .assertValue(emptyList()) 115 | .assertComplete(); 116 | } 117 | 118 | @Test public void mapToListReturnsNullOnMapperNull() { 119 | Function1 mapToNull = new Function1() { 120 | private int count; 121 | 122 | @Override public Employee invoke(Cursor cursor) { 123 | return count++ == 2 ? null : Employee.MAPPER.invoke(cursor); 124 | } 125 | }; 126 | just(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson", "eve", "Eve Evenson")) 127 | .to(o -> RxContentResolver.mapToList(o, mapToNull)) // 128 | .test() 129 | .assertValue(asList( 130 | new Employee("alice", "Alice Allison"), 131 | new Employee("bob", "Bob Bobberson"), 132 | null)) 133 | .assertComplete(); 134 | } 135 | 136 | @Test public void mapToListIgnoresNullCursor() { 137 | just(NullQuery.INSTANCE) 138 | .to(o -> RxContentResolver.mapToList(o, Employee.MAPPER)) 139 | .test() 140 | .assertNoValues() 141 | .assertComplete(); 142 | } 143 | 144 | @SdkSuppress(minSdkVersion = 24) 145 | @Test public void mapToOptional() { 146 | just(queryOf("alice", "Alice Allison")) 147 | .to(o -> RxContentResolver.mapToOptional(o, Employee.MAPPER)) 148 | .test() 149 | .assertValue(Optional.of(new Employee("alice", "Alice Allison"))); 150 | } 151 | 152 | @SdkSuppress(minSdkVersion = 24) 153 | @Test public void mapToOptionalThrowsWhenMapperReturnsNull() { 154 | just(queryOf("alice", "Alice Allison")) 155 | .to(o -> RxContentResolver.mapToOptional(o, c -> null)) 156 | .test() 157 | .assertError(t -> { 158 | return t instanceof NullPointerException 159 | && t.getMessage().equals("QueryToOne mapper returned null"); 160 | }); 161 | } 162 | 163 | @SdkSuppress(minSdkVersion = 24) 164 | @Test public void mapToOptionalThrowsOnMultipleRows() { 165 | just(queryOf("alice", "Alice Allison", "bob", "Bob Bobberson")) 166 | .to(o -> RxContentResolver.mapToOptional(o, Employee.MAPPER)) 167 | .test() 168 | .assertError(t -> { 169 | return t instanceof IllegalStateException 170 | && t.getMessage().equals("Cursor returned more than 1 row"); 171 | }); 172 | } 173 | 174 | @SdkSuppress(minSdkVersion = 24) 175 | @Test public void mapToOptionalIgnoresNullCursor() { 176 | just(NullQuery.INSTANCE) 177 | .to(o -> RxContentResolver.mapToOptional(o, Employee.MAPPER)) 178 | .test() 179 | .assertValue(Optional.empty()); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /copper-rx2/src/main/java/app/cash/copper/rx2/RxContentResolver.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | @file:JvmName("RxContentResolver") 17 | 18 | package app.cash.copper.rx2 19 | 20 | import android.content.ContentResolver 21 | import android.database.ContentObserver 22 | import android.database.Cursor 23 | import android.net.Uri 24 | import android.os.Handler 25 | import android.os.Looper 26 | import androidx.annotation.CheckResult 27 | import androidx.annotation.RequiresApi 28 | import app.cash.copper.ContentResolverQuery 29 | import app.cash.copper.Query 30 | import io.reactivex.Observable 31 | import io.reactivex.ObservableSource 32 | import io.reactivex.Scheduler 33 | import io.reactivex.schedulers.Schedulers 34 | import java.util.Optional 35 | 36 | /** 37 | * Create an observable which will notify subscribers with a [query][Query] for 38 | * execution. Subscribers are responsible for **always** closing [Cursor] instance 39 | * returned from the [Query]. 40 | * 41 | * Subscribers will receive an immediate notification for initial data as well as subsequent 42 | * notifications for when the supplied `uri`'s data changes. Unsubscribe when you no longer 43 | * want updates to a query. 44 | * 45 | * Since content resolver triggers are inherently asynchronous, items emitted from the returned 46 | * observable use [scheduler] which defaults to [Schedulers.io]. For consistency, the immediate 47 | * notification sent on subscribe also uses this scheduler. As such, calling 48 | * [subscribeOn][Observable.subscribeOn] on the returned observable has no effect. 49 | * 50 | * Note: To skip the immediate notification and only receive subsequent notifications when data 51 | * has changed call `skip(1)` on the returned observable. 52 | * 53 | * **Warning:** this method does not perform the query! Only by subscribing to the returned 54 | * [Observable] will the operation occur. 55 | * 56 | * @see ContentResolver.query 57 | * @see ContentResolver.registerContentObserver 58 | */ 59 | @CheckResult 60 | @JvmOverloads 61 | fun ContentResolver.observeQuery( 62 | uri: Uri, 63 | projection: Array? = null, 64 | selection: String? = null, 65 | selectionArgs: Array? = null, 66 | sortOrder: String? = null, 67 | notifyForDescendants: Boolean = false, 68 | scheduler: Scheduler = Schedulers.io() 69 | ): Observable { 70 | val query = ContentResolverQuery(this, uri, projection, selection, selectionArgs, sortOrder) 71 | val queries = 72 | Observable.create { e -> 73 | val observer = object : ContentObserver(mainThread) { 74 | override fun onChange(selfChange: Boolean) { 75 | if (!e.isDisposed) { 76 | e.onNext(query) 77 | } 78 | } 79 | } 80 | registerContentObserver(uri, notifyForDescendants, observer) 81 | e.setCancellable { unregisterContentObserver(observer) } 82 | if (!e.isDisposed) { 83 | e.onNext(query) // Trigger initial query. 84 | } 85 | } 86 | return queries.observeOn(scheduler) 87 | } 88 | 89 | private val mainThread = Handler(Looper.getMainLooper()) 90 | 91 | /** 92 | * Execute the query on the underlying database and return an Observable of each row mapped to 93 | * `T` by `mapper`. 94 | * 95 | * Standard usage of this operation is in `flatMap`: 96 | * ``` 97 | * flatMap(q -> q.asRows(Item.MAPPER).toList()) 98 | * ``` 99 | * 100 | * However, the above is a more-verbose but identical operation as 101 | * [mapToList]. This `asRows` method should be used when you need 102 | * to limit or filter the items separate from the actual query. 103 | * ```flatMap(q -> q.asRows(Item.MAPPER).take(5).toList()) 104 | * // or... 105 | * flatMap(q -> q.asRows(Item.MAPPER).filter(i -> i.isActive).toList()) 106 | * ``` 107 | * 108 | * Note: Limiting results or filtering will almost always be faster in the database as part of 109 | * a query and should be preferred, where possible. 110 | * 111 | * The resulting observable will be empty if `null` is returned from [run]. 112 | */ 113 | @CheckResult 114 | fun Query.asRows(mapper: (Cursor) -> T): Observable { 115 | return Observable.create { e -> 116 | run()?.use { cursor -> 117 | while (cursor.moveToNext() && !e.isDisposed) { 118 | e.onNext(mapper(cursor)) 119 | } 120 | } 121 | if (!e.isDisposed) { 122 | e.onComplete() 123 | } 124 | } 125 | } 126 | 127 | /** 128 | * Transforms a query observable returning a single row to a `T` using [mapper]. 129 | * 130 | * It is an error for a query to pass through this operator with more than 1 row in its result 131 | * set. Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows 132 | * emit [default], or do not emit if [default] is null. 133 | * 134 | * This operator ignores `null` cursors returned from [run]. 135 | * 136 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 137 | */ 138 | @CheckResult 139 | @JvmOverloads 140 | fun ObservableSource.mapToOne( 141 | default: T? = null, 142 | mapper: (Cursor) -> T 143 | ): Observable { 144 | return QueryToOneObservable(this, mapper, default) 145 | } 146 | 147 | /** 148 | * Transforms a query observable returning a single row to a `Optional` using `mapper`. 149 | * 150 | * It is an error for a query to pass through this operator with more than 1 row in its result 151 | * set. Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows 152 | * emit [Optional.empty()][Optional.empty]. 153 | * 154 | * This operator ignores `null` cursors returned from [run]. 155 | * 156 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 157 | */ 158 | @RequiresApi(24) 159 | @CheckResult 160 | fun ObservableSource.mapToOptional( 161 | mapper: (Cursor) -> T 162 | ): Observable> { 163 | return QueryToOptionalObservable(this, mapper) 164 | } 165 | 166 | /** 167 | * Transforms a query observable to a `List` using `mapper`. 168 | * 169 | * Be careful using this operator as it will always consume the entire cursor and create objects 170 | * for each row, every time this observable emits a new query. On tables whose queries update 171 | * frequently or very large result sets this can result in the creation of many objects. 172 | * 173 | * This operator ignores `null` cursors returned from [run]. 174 | * 175 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 176 | */ 177 | @CheckResult 178 | fun ObservableSource.mapToList( 179 | mapper: (Cursor) -> T 180 | ): Observable> { 181 | return QueryToListObservable(this, mapper) 182 | } 183 | -------------------------------------------------------------------------------- /copper-rx3/src/main/java/app/cash/copper/rx3/RxContentResolver.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 Square, Inc. 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 | @file:JvmName("RxContentResolver") 17 | 18 | package app.cash.copper.rx3 19 | 20 | import android.content.ContentResolver 21 | import android.database.ContentObserver 22 | import android.database.Cursor 23 | import android.net.Uri 24 | import android.os.Handler 25 | import android.os.Looper 26 | import androidx.annotation.CheckResult 27 | import androidx.annotation.RequiresApi 28 | import app.cash.copper.ContentResolverQuery 29 | import app.cash.copper.Query 30 | import io.reactivex.rxjava3.core.Observable 31 | import io.reactivex.rxjava3.core.ObservableSource 32 | import io.reactivex.rxjava3.core.Scheduler 33 | import io.reactivex.rxjava3.schedulers.Schedulers 34 | import java.util.Optional 35 | 36 | /** 37 | * Create an observable which will notify subscribers with a [query][Query] for 38 | * execution. Subscribers are responsible for **always** closing [Cursor] instance 39 | * returned from the [Query]. 40 | * 41 | * Subscribers will receive an immediate notification for initial data as well as subsequent 42 | * notifications for when the supplied `uri`'s data changes. Unsubscribe when you no longer 43 | * want updates to a query. 44 | * 45 | * Since content resolver triggers are inherently asynchronous, items emitted from the returned 46 | * observable use [scheduler] which defaults to [Schedulers.io]. For consistency, the immediate 47 | * notification sent on subscribe also uses this scheduler. As such, calling 48 | * [subscribeOn][Observable.subscribeOn] on the returned observable has no effect. 49 | * 50 | * Note: To skip the immediate notification and only receive subsequent notifications when data 51 | * has changed call `skip(1)` on the returned observable. 52 | * 53 | * **Warning:** this method does not perform the query! Only by subscribing to the returned 54 | * [Observable] will the operation occur. 55 | * 56 | * @see ContentResolver.query 57 | * @see ContentResolver.registerContentObserver 58 | */ 59 | @CheckResult 60 | @JvmOverloads 61 | fun ContentResolver.observeQuery( 62 | uri: Uri, 63 | projection: Array? = null, 64 | selection: String? = null, 65 | selectionArgs: Array? = null, 66 | sortOrder: String? = null, 67 | notifyForDescendants: Boolean = false, 68 | scheduler: Scheduler = Schedulers.io() 69 | ): Observable { 70 | val query = ContentResolverQuery(this, uri, projection, selection, selectionArgs, sortOrder) 71 | val queries = 72 | Observable.create { e -> 73 | val observer = object : ContentObserver(mainThread) { 74 | override fun onChange(selfChange: Boolean) { 75 | if (!e.isDisposed) { 76 | e.onNext(query) 77 | } 78 | } 79 | } 80 | registerContentObserver(uri, notifyForDescendants, observer) 81 | e.setCancellable { unregisterContentObserver(observer) } 82 | if (!e.isDisposed) { 83 | e.onNext(query) // Trigger initial query. 84 | } 85 | } 86 | return queries.observeOn(scheduler) 87 | } 88 | 89 | private val mainThread = Handler(Looper.getMainLooper()) 90 | 91 | /** 92 | * Execute the query on the underlying database and return an Observable of each row mapped to 93 | * `T` by `mapper`. 94 | * 95 | * Standard usage of this operation is in `flatMap`: 96 | * ``` 97 | * flatMap(q -> q.asRows(Item.MAPPER).toList()) 98 | * ``` 99 | * 100 | * However, the above is a more-verbose but identical operation as 101 | * [mapToList]. This `asRows` method should be used when you need 102 | * to limit or filter the items separate from the actual query. 103 | * ```flatMap(q -> q.asRows(Item.MAPPER).take(5).toList()) 104 | * // or... 105 | * flatMap(q -> q.asRows(Item.MAPPER).filter(i -> i.isActive).toList()) 106 | * ``` 107 | * 108 | * Note: Limiting results or filtering will almost always be faster in the database as part of 109 | * a query and should be preferred, where possible. 110 | * 111 | * The resulting observable will be empty if `null` is returned from [run]. 112 | */ 113 | @CheckResult 114 | fun Query.asRows(mapper: (Cursor) -> T): Observable { 115 | return Observable.create { e -> 116 | run()?.use { cursor -> 117 | while (cursor.moveToNext() && !e.isDisposed) { 118 | e.onNext(mapper(cursor)) 119 | } 120 | } 121 | if (!e.isDisposed) { 122 | e.onComplete() 123 | } 124 | } 125 | } 126 | 127 | /** 128 | * Transforms a query observable returning a single row to a `T` using [mapper]. 129 | * 130 | * It is an error for a query to pass through this operator with more than 1 row in its result 131 | * set. Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows 132 | * emit [default], or do not emit if [default] is null. 133 | * 134 | * This operator ignores `null` cursors returned from [run]. 135 | * 136 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 137 | */ 138 | @CheckResult 139 | @JvmOverloads 140 | fun ObservableSource.mapToOne( 141 | default: T? = null, 142 | mapper: (Cursor) -> T 143 | ): Observable { 144 | return QueryToOneObservable(this, mapper, default) 145 | } 146 | 147 | /** 148 | * Transforms a query observable returning a single row to a `Optional` using `mapper`. 149 | * 150 | * It is an error for a query to pass through this operator with more than 1 row in its result 151 | * set. Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows 152 | * emit [Optional.empty()][Optional.empty]. 153 | * 154 | * This operator ignores `null` cursors returned from [run]. 155 | * 156 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 157 | */ 158 | @RequiresApi(24) 159 | @CheckResult 160 | fun ObservableSource.mapToOptional( 161 | mapper: (Cursor) -> T 162 | ): Observable> { 163 | return QueryToOptionalObservable(this, mapper) 164 | } 165 | 166 | /** 167 | * Transforms a query observable to a `List` using `mapper`. 168 | * 169 | * Be careful using this operator as it will always consume the entire cursor and create objects 170 | * for each row, every time this observable emits a new query. On tables whose queries update 171 | * frequently or very large result sets this can result in the creation of many objects. 172 | * 173 | * This operator ignores `null` cursors returned from [run]. 174 | * 175 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 176 | */ 177 | @CheckResult 178 | fun ObservableSource.mapToList( 179 | mapper: (Cursor) -> T 180 | ): Observable> { 181 | return QueryToListObservable(this, mapper) 182 | } 183 | -------------------------------------------------------------------------------- /copper-flow/src/main/java/app/cash/copper/flow/FlowContentResolver.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 Square, Inc. 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 | @file:JvmName("FlowContentResolver") 17 | 18 | package app.cash.copper.flow 19 | 20 | import android.content.ContentResolver 21 | import android.database.ContentObserver 22 | import android.database.Cursor 23 | import android.net.Uri 24 | import android.os.Handler 25 | import android.os.Looper 26 | import androidx.annotation.CheckResult 27 | import app.cash.copper.ContentResolverQuery 28 | import app.cash.copper.Query 29 | import kotlinx.coroutines.CoroutineDispatcher 30 | import kotlinx.coroutines.Dispatchers 31 | import kotlinx.coroutines.ExperimentalCoroutinesApi 32 | import kotlinx.coroutines.channels.Channel 33 | import kotlinx.coroutines.channels.Channel.Factory.CONFLATED 34 | import kotlinx.coroutines.channels.Channel.Factory.RENDEZVOUS 35 | import kotlinx.coroutines.flow.Flow 36 | import kotlinx.coroutines.flow.buffer 37 | import kotlinx.coroutines.flow.channelFlow 38 | import kotlinx.coroutines.flow.flow 39 | import kotlinx.coroutines.flow.transform 40 | import kotlinx.coroutines.withContext 41 | 42 | /** 43 | * Create an observable which will notify subscribers with a [query][Query] for 44 | * execution. Collectors are responsible for **always** closing [Cursor] instance 45 | * returned from the [Query]. 46 | * 47 | * Subscribers will receive an immediate notification for initial data as well as subsequent 48 | * notifications for when the supplied `uri`'s data changes. Unsubscribe when you no longer 49 | * want updates to a query. 50 | * 51 | * Note: To skip the immediate notification and only receive subsequent notifications when data 52 | * has changed call `drop(1)` on the returned observable. 53 | * 54 | * **Warning:** this method does not perform the query! Only by collecting the returned [Flow] will 55 | * the operation occur. 56 | * 57 | * @see ContentResolver.query 58 | * @see ContentResolver.registerContentObserver 59 | */ 60 | @CheckResult 61 | fun ContentResolver.observeQuery( 62 | uri: Uri, 63 | projection: Array? = null, 64 | selection: String? = null, 65 | selectionArgs: Array? = null, 66 | sortOrder: String? = null, 67 | notifyForDescendants: Boolean = false 68 | ): Flow { 69 | val query = ContentResolverQuery(this, uri, projection, selection, selectionArgs, sortOrder) 70 | return flow { 71 | emit(query) 72 | 73 | val channel = Channel(CONFLATED) 74 | val observer = object : ContentObserver(mainThread) { 75 | override fun onChange(selfChange: Boolean) { 76 | channel.trySend(Unit) 77 | } 78 | } 79 | 80 | registerContentObserver(uri, notifyForDescendants, observer) 81 | try { 82 | for (item in channel) { 83 | emit(query) 84 | } 85 | } finally { 86 | unregisterContentObserver(observer) 87 | } 88 | } 89 | } 90 | 91 | private val mainThread = Handler(Looper.getMainLooper()) 92 | 93 | /** 94 | * Execute the query on the underlying database and return a flow of each row mapped to 95 | * `T` by `mapper`. 96 | * 97 | * Standard usage of this operation is in `flatMap`: 98 | * ``` 99 | * flatMap(q -> q.asRows(Item.MAPPER).toList()) 100 | * ``` 101 | * 102 | * However, the above is a more-verbose but identical operation as 103 | * [mapToList]. This `asRows` function should be used when you need 104 | * to limit or filter the items separate from the actual query. 105 | * ```flatMap(q -> q.asRows(Item.MAPPER).take(5).toList()) 106 | * // or... 107 | * flatMap(q -> q.asRows(Item.MAPPER).filter(i -> i.isActive).toList()) 108 | * ``` 109 | * 110 | * Note: Limiting results or filtering will almost always be faster in the database as part of 111 | * a query and should be preferred, where possible. 112 | * 113 | * The resulting flow will be empty if `null` is returned from [Query.run]. 114 | */ 115 | @ExperimentalCoroutinesApi // Relies on channelFlow. 116 | @CheckResult 117 | fun Query.asRows( 118 | dispatcher: CoroutineDispatcher = Dispatchers.IO, 119 | mapper: (Cursor) -> T 120 | ): Flow { 121 | return channelFlow { 122 | withContext(dispatcher) { 123 | run()?.use { cursor -> 124 | while (cursor.moveToNext()) { 125 | send(mapper(cursor)) 126 | } 127 | } 128 | } 129 | }.buffer(RENDEZVOUS) 130 | } 131 | 132 | /** 133 | * Transforms a query flow returning a single row to a `T` using [mapper]. 134 | * 135 | * It is an error for a query to pass through this operator with more than 1 row in its result 136 | * set. Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows 137 | * emit [default], or do not emit if [default] is null. 138 | * 139 | * This operator ignores `null` cursors returned from [Query.run]. 140 | * 141 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 142 | */ 143 | @CheckResult 144 | fun Flow.mapToOne( 145 | default: T? = null, 146 | dispatcher: CoroutineDispatcher = Dispatchers.IO, 147 | mapper: (Cursor) -> T 148 | ): Flow = transform { query -> 149 | val item = withContext(dispatcher) { 150 | query.run()?.use { cursor -> 151 | if (cursor.moveToNext()) { 152 | val item = mapper(cursor) 153 | check(!cursor.moveToNext()) { "Cursor returned more than 1 row" } 154 | item 155 | } else { 156 | default 157 | } 158 | } 159 | } 160 | if (item != null) { 161 | emit(item) 162 | } 163 | } 164 | 165 | /** 166 | * Transforms a query flow returning a single row to a `T?` using `mapper`. 167 | * 168 | * It is an error for a query to pass through this operator with more than 1 row in its result 169 | * set. Use `LIMIT 1` on the underlying SQL query to prevent this. Result sets with 0 rows 170 | * emit null. 171 | * 172 | * This operator ignores `null` cursors returned from [Query.run]. 173 | * 174 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 175 | */ 176 | @CheckResult 177 | fun Flow.mapToOneOrNull( 178 | dispatcher: CoroutineDispatcher = Dispatchers.IO, 179 | mapper: (Cursor) -> T 180 | ): Flow = transform { query -> 181 | val (emit, item) = withContext(dispatcher) { 182 | val cursor = query.run() 183 | if (cursor == null) { 184 | false to null 185 | } else { 186 | cursor.use { 187 | val item = if (cursor.moveToNext()) { 188 | val item = mapper(cursor) 189 | check(!cursor.moveToNext()) { "Cursor returned more than 1 row" } 190 | item 191 | } else { 192 | null 193 | } 194 | true to item 195 | } 196 | } 197 | } 198 | if (emit) { 199 | emit(item) 200 | } 201 | } 202 | 203 | /** 204 | * Transforms a query flow to a `List` using `mapper`. 205 | * 206 | * Be careful using this operator as it will always consume the entire cursor and create objects 207 | * for each row, every time this observable emits a new query. On tables whose queries update 208 | * frequently or very large result sets this can result in the creation of many objects. 209 | * 210 | * This operator ignores `null` cursors returned from [Query.run]. 211 | * 212 | * @param mapper Maps the current [Cursor] row to `T`. May not return null. 213 | */ 214 | @CheckResult 215 | fun Flow.mapToList( 216 | dispatcher: CoroutineDispatcher = Dispatchers.IO, 217 | mapper: (Cursor) -> T 218 | ): Flow> = transform { query -> 219 | val list = withContext(dispatcher) { 220 | query.run()?.use { cursor -> 221 | val items = ArrayList(cursor.count) 222 | while (cursor.moveToNext()) { 223 | items.add(mapper(cursor)) 224 | } 225 | items 226 | } 227 | } 228 | if (list != null) { 229 | emit(list) 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | 118 | 119 | # Determine the Java command to use to start the JVM. 120 | if [ -n "$JAVA_HOME" ] ; then 121 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 122 | # IBM's JDK on AIX uses strange locations for the executables 123 | JAVACMD=$JAVA_HOME/jre/sh/java 124 | else 125 | JAVACMD=$JAVA_HOME/bin/java 126 | fi 127 | if [ ! -x "$JAVACMD" ] ; then 128 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 129 | 130 | Please set the JAVA_HOME variable in your environment to match the 131 | location of your Java installation." 132 | fi 133 | else 134 | JAVACMD=java 135 | if ! command -v java >/dev/null 2>&1 136 | then 137 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 138 | 139 | Please set the JAVA_HOME variable in your environment to match the 140 | location of your Java installation." 141 | fi 142 | fi 143 | 144 | # Increase the maximum file descriptors if we can. 145 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 146 | case $MAX_FD in #( 147 | max*) 148 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 149 | # shellcheck disable=SC2039,SC3045 150 | MAX_FD=$( ulimit -H -n ) || 151 | warn "Could not query maximum file descriptor limit" 152 | esac 153 | case $MAX_FD in #( 154 | '' | soft) :;; #( 155 | *) 156 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 157 | # shellcheck disable=SC2039,SC3045 158 | ulimit -n "$MAX_FD" || 159 | warn "Could not set maximum file descriptor limit to $MAX_FD" 160 | esac 161 | fi 162 | 163 | # Collect all arguments for the java command, stacking in reverse order: 164 | # * args from the command line 165 | # * the main class name 166 | # * -classpath 167 | # * -D...appname settings 168 | # * --module-path (only if needed) 169 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 170 | 171 | # For Cygwin or MSYS, switch paths to Windows format before running java 172 | if "$cygwin" || "$msys" ; then 173 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------