├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── android.gradle ├── asyncawait-android ├── build.gradle └── src │ ├── androidTest │ └── kotlin │ │ └── com │ │ └── nhaarman │ │ └── async │ │ └── AsyncAndroidTest.kt │ ├── main │ ├── AndroidManifest.xml │ └── kotlin │ │ └── com │ │ └── nhaarman │ │ └── async │ │ ├── AsyncController.kt │ │ ├── Cancelable.kt │ │ ├── CancelableCall.kt │ │ ├── RunOnUi.kt │ │ └── Task.kt │ └── test │ ├── kotlin │ └── com │ │ └── nhaarman │ │ └── async │ │ └── AsyncTest.kt │ └── resources │ └── mockito-extensions │ └── org.mockito.plugins.MockMaker ├── build.gradle ├── dependencies.gradle ├── gradle.properties ├── gradle ├── scripts │ ├── publishing.gradle │ └── tagging.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | captures 2 | **/bin/* 3 | **/target/* 4 | **/gen/* 5 | **/build/* 6 | **/.idea/* 7 | **/*.iml 8 | .gradle 9 | /local.properties 10 | /.idea/workspace.xml 11 | .DS_Store 12 | .metadata/* 13 | */com_crashlytics_export_strings.xml 14 | **/com_crashlytics_export_strings.xml 15 | **/crashlytics-build.properties 16 | **/crashlytics.properties 17 | 18 | *.orig 19 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | jdk: 3 | - oraclejdk8 4 | 5 | android: 6 | components: 7 | - tools 8 | - tools 9 | - platform-tools 10 | - build-tools-25.0.0 11 | - android-25 12 | - extra-google-google_play_services 13 | - extra-google-m2repository 14 | - extra-android-m2repository 15 | licenses: 16 | - 'android-sdk-license-.+' 17 | 18 | before_install: 19 | - echo 'android.builder.sdkDownload=false' > gradle.properties 20 | 21 | # Emulator Management: Create, Start and Wait 22 | before_script: 23 | - echo no | android create avd --force -n test -t android-21 --abi armeabi-v7a 24 | - emulator -avd test -no-audio -no-window & 25 | - android-wait-for-emulator 26 | - adb shell input keyevent 82 & 27 | 28 | script: 29 | - ./gradlew test connectedCheck dokka -PisRelease=false 30 | 31 | notifications: 32 | email: false 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AsyncAwait-Android 2 | [ ![Download](https://maven-badges.herokuapp.com/maven-central/com.nhaarman/asyncawait-android/badge.svg) ](https://maven-badges.herokuapp.com/maven-central/com.nhaarman/asyncawait-android) 3 | 4 | **Warning!** 5 | This library was created for Kotlin 1.1-M03. Since M04, the API has changed. See [Kotlin-Coroutines](https://github.com/Kotlin/kotlin-coroutines) for more info. 6 | 7 | A library that provides the async/await concept for Android using the coroutines feature in Kotlin 1.1. 8 | 9 | ## Install 10 | 11 | AsyncAwait-Android is available on Maven Central. 12 | For Gradle users, add the following to your `build.gradle`, replacing `x.x.x` with the latest version: 13 | 14 | ```groovy 15 | repositories { 16 | mavenCentral() 17 | } 18 | dependencies { 19 | compile "com.nhaarman:asyncawait-android:x.x.x" 20 | } 21 | ``` 22 | 23 | AsyncAwait-Android uses the 1.1-M03 eap of Kotlin. See the [How to try it](https://blog.jetbrains.com/kotlin/2016/07/first-glimpse-of-kotlin-1-1-coroutines-type-aliases-and-more/) section for details. 24 | 25 | ## Example 26 | 27 | A typical scenario is provided below: 28 | 29 | ```kotlin 30 | 31 | fun onCreate(savedInstanceState: Bundle?) { 32 | super.onCreate(savedInstanceState) 33 | 34 | asyncUI { 35 | val textView = TextView(this@MainActivity) 36 | setContentView(textView) 37 | val githubUserName = await(retrieveGithubUser()).name 38 | textView.text = githubUserName 39 | } 40 | } 41 | 42 | fun retrieveGithubUser() = async { 43 | ... 44 | } 45 | 46 | ``` 47 | 48 | In this snippet the coroutine is suspended at `await(retrieveGithubUser())`, and 49 | resumed when the task returned by `retrieveGithubUser()` finishes. 50 | The coroutine is resumed on the main thread, as indicated by `asyncUI`. 51 | 52 | 53 | ## How it works 54 | _Inspired by http://blog.stephencleary.com/2012/02/async-and-await.html._ 55 | 56 | An asynchronous method looks something like this: 57 | 58 | ```kotlin 59 | fun foo() = async { 60 | await(delay(1, SECONDS)) 61 | "bar" 62 | } 63 | ``` 64 | 65 | The call to `async` provides access to the `await` function, and changes the way the method is executed. 66 | It does _not_ move the method call on another thread. 67 | The method is executed synchronously until the first call to `await`, which _may_ result in an asynchronous call. 68 | 69 | If the parameter provided to `await` has already completed, the method continuous running synchronously. 70 | If the parameter has not yet completed, `await` tells the awaitable to run the rest of the method when it completes, and then returns from the async method. 71 | 72 | Later on, when the awaitable completes, it will execute the remainder of the async method. 73 | The thread on which the remainder is executed is determined by whether the async method was called by `async` or `asyncUI` 74 | 75 | ## Async 76 | 77 | There are two flavors of `async`: one that takes in a parameter (e.g. `async`), and one that does not. 78 | The type passed to `async` determines the result type of the coroutine. 79 | 80 | When using `async`, the coroutine will continue on the thread the awaitable ended on. 81 | For example, if you call `await` with a `Task` that is executed on some io thread, the remainder of the coroutine will continue on that io thread: 82 | 83 | ``` 84 | fun foo() = async { 85 | // Runs on calling thread 86 | await(someIoTask()) // someIoTask() runs on an io thread 87 | // Continues on the io thread 88 | } 89 | ``` 90 | 91 | ## AsyncUI 92 | 93 | If you want to modify UI elements, or do other things that require you to be on the main thread, you can use `asyncUI`. 94 | In contrast to `async`, `asyncUI` _does_ continue on the main thread after a call to `await`: 95 | 96 | ``` 97 | // Runs on main thread 98 | await(someIoTask()) // someIoTask() runs on an io thread 99 | // Continues on the main thread 100 | ``` 101 | 102 | ## Await 103 | 104 | Inside a coroutine, you can await on a `Task` or pass a lambda. 105 | Since `async` returns a `Task`, you can await on asynchronous methods. 106 | The return type of `await` is either the type parameter passed to `Task` or the return type of the lambda. 107 | 108 | When awaiting on a `Task`, there is no thread switching, unless specified explicitly by that task. 109 | When awaiting on a lambda, the lambda _will_ be executed on another thread: 110 | 111 | ```kotlin 112 | fun foo() = asyncUI { 113 | // Main thread 114 | var result = await(bar()) // bar() is executed on the main thread 115 | // Main thread 116 | result = await { // Lambda is executed on another thread 117 | "Bar" 118 | } 119 | // Main thread 120 | } 121 | 122 | fun bar() = async { 123 | "Bar" 124 | } 125 | ``` 126 | -------------------------------------------------------------------------------- /android.gradle: -------------------------------------------------------------------------------- 1 | project.android.compileSdkVersion 25; 2 | project.android.buildToolsVersion "25.0.0" 3 | 4 | project.android.defaultConfig.minSdkVersion 16 5 | project.android.defaultConfig.targetSdkVersion 25 6 | 7 | project.android.lintOptions.warningsAsErrors = true 8 | project.android.lintOptions.textReport = true 9 | 10 | project.android.sourceSets.main.java.srcDirs += 'src/main/kotlin' 11 | project.android.sourceSets.androidTest.java.srcDirs += 'src/androidTest/kotlin' 12 | project.android.sourceSets.test.java.srcDirs += 'src/test/kotlin' 13 | 14 | project.android.testOptions.unitTests.returnDefaultValues = true 15 | -------------------------------------------------------------------------------- /asyncawait-android/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: "com.android.library" 2 | apply plugin: "kotlin-android" 3 | apply plugin: "org.jetbrains.dokka" 4 | apply from: rootProject.projectDir.absolutePath + '/android.gradle'; 5 | apply from: "../gradle/scripts/publishing.gradle" 6 | 7 | android { 8 | defaultConfig { 9 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 10 | } 11 | } 12 | 13 | dependencies { 14 | compile kotlinStdLib 15 | provided retrofit2 16 | provided rxJava1 17 | provided rxJava2 18 | 19 | testCompile junit 20 | testCompile expectKt 21 | testCompile mockitoKotlin 22 | 23 | androidTestCompile junit 24 | androidTestCompile expectKt 25 | androidTestCompile androidSupportTestRunner 26 | androidTestCompile androidSupportTestRules 27 | } 28 | 29 | dokka { 30 | outputFormat = "html" 31 | outputDirectory = "$buildDir/javadoc" 32 | sourceDirs = files("src/main/kotlin") 33 | 34 | linkMapping { 35 | dir = "src/main/kotlin" 36 | url = "https://github.com/nhaarman/asyncawait-android/tree/master/asyncawait-android/src/main/kotlin" 37 | suffix = "#L" 38 | } 39 | } -------------------------------------------------------------------------------- /asyncawait-android/src/androidTest/kotlin/com/nhaarman/async/AsyncAndroidTest.kt: -------------------------------------------------------------------------------- 1 | package com.nhaarman.async 2 | 3 | import android.os.Looper 4 | import android.support.test.runner.AndroidJUnit4 5 | import com.nhaarman.expect.expect 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | import java.util.concurrent.TimeUnit.SECONDS 9 | 10 | 11 | @RunWith(AndroidJUnit4::class) 12 | class AsyncAndroidTest { 13 | 14 | private val resultString = "result" 15 | 16 | @Test 17 | fun returnToMainThread_fromAwait() { 18 | /* Given */ 19 | var a: String? = null 20 | 21 | /* When */ 22 | asyncUI { 23 | a = await { 24 | expect(Looper.myLooper()).toNotBeTheSameAs(Looper.getMainLooper()) 25 | resultString 26 | } 27 | /* Then */ 28 | expect(Looper.myLooper()).toBeTheSameAs(Looper.getMainLooper()) 29 | }.wait() 30 | 31 | /* Then */ 32 | expect(a).toBe(resultString) 33 | } 34 | 35 | @Test 36 | fun awaitOnAsyncUI() { 37 | /* Given */ 38 | var a: String? = null 39 | 40 | /* When */ 41 | async { 42 | a = await(asyncUI { 43 | val result = await { 44 | "String" 45 | } 46 | expect(Looper.myLooper()).toBeTheSameAs(Looper.getMainLooper()) 47 | result 48 | }) 49 | }.wait(5, SECONDS) 50 | 51 | /* Then */ 52 | expect(a).toBe("String") 53 | } 54 | } 55 | 56 | -------------------------------------------------------------------------------- /asyncawait-android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /asyncawait-android/src/main/kotlin/com/nhaarman/async/AsyncController.kt: -------------------------------------------------------------------------------- 1 | package com.nhaarman.async 2 | 3 | import android.os.Looper 4 | import io.reactivex.disposables.Disposable 5 | import retrofit2.Call 6 | import retrofit2.Response 7 | import java.util.concurrent.Executors 8 | import java.util.concurrent.TimeUnit 9 | import kotlin.reflect.KProperty 10 | import io.reactivex.Single as Single2 11 | import rx.Single as Single1 12 | import rx.Subscription as Subscription1 13 | 14 | /** 15 | * Run asynchronous computations based on [c] coroutine parameter. 16 | * 17 | * Execution starts immediately within the 'async' call and it runs until 18 | * the first suspension point is reached (an 'await' call). 19 | * The remaining part of the coroutine will be executed as the awaited code 20 | * is completed. 21 | * There is no thread switching after 'await' calls. 22 | * 23 | * @param c a coroutine representing asynchronous computations 24 | * @param T the return type of the coroutine. 25 | * 26 | * @return Task object representing result of computations 27 | */ 28 | fun async(coroutine c: AsyncController.() -> Continuation): Task { 29 | val controller = AsyncController() 30 | controller.c().resume(Unit) 31 | return controller.task 32 | } 33 | 34 | /** 35 | * Run asynchronous computations based on [c] coroutine parameter. 36 | * 37 | * Execution starts immediately within the 'async' call and it runs until 38 | * the first suspension point is reached (an 'await' call). 39 | * The remaining part of the coroutine will be executed as the awaited code 40 | * is completed. 41 | * There is no thread switching after 'await' calls. 42 | * 43 | * @param c a coroutine representing asynchronous computations 44 | * 45 | * @return Task object representing result of computations 46 | */ 47 | @JvmName("asyncWithoutParameter") 48 | fun async(coroutine c: AsyncController.() -> Continuation): Task { 49 | val controller = AsyncController() 50 | controller.c().resume(Unit) 51 | return controller.task 52 | } 53 | 54 | /** 55 | * Run asynchronous computations based on [c] coroutine parameter. 56 | * 57 | * Execution starts immediately within the 'async' call and it runs until 58 | * the first suspension point is reached (an 'await' call). 59 | * The remaining part of the coroutine will be executed *on the main thread* 60 | * as the awaited code is completed. 61 | * 62 | * @param c a coroutine representing asynchronous computations 63 | * @param T the return type of the coroutine. 64 | * 65 | * @return Task object representing result of computations 66 | */ 67 | fun asyncUI(coroutine c: AsyncController.() -> Continuation): Task { 68 | val controller = AsyncController(returnToMainThread = true) 69 | controller.c().resume(Unit) 70 | return controller.task 71 | } 72 | 73 | /** 74 | * Run asynchronous computations based on [c] coroutine parameter. 75 | * 76 | * Execution starts immediately within the 'async' call and it runs until 77 | * the first suspension point is reached (an 'await' call). 78 | * The remaining part of the coroutine will be executed *on the main thread* 79 | * as the awaited code is completed. 80 | * 81 | * @param c a coroutine representing asynchronous computations 82 | * 83 | * @return Task object representing result of computations 84 | */ 85 | @JvmName("asyncUIWithoutParameter") 86 | fun asyncUI(coroutine c: AsyncController.() -> Continuation): Task { 87 | val controller = AsyncController(returnToMainThread = true) 88 | controller.c().resume(Unit) 89 | return controller.task 90 | } 91 | 92 | /** 93 | * Returns a [Task] that completes after a specified time interval. 94 | * 95 | * @param time the delay to wait before completing the returned task. 96 | * @param unit the [TimeUnit] in which [time] is defined. 97 | * 98 | * @return a cancelable [Task]. 99 | */ 100 | fun delay(time: Long, unit: TimeUnit): Task { 101 | return Task().apply { 102 | val task = this 103 | startedWith(executorService.submit { 104 | Thread.sleep(unit.toMillis(time)) 105 | task.complete(Unit) 106 | }) 107 | } 108 | } 109 | 110 | class AsyncController(private val returnToMainThread: Boolean = false) { 111 | 112 | internal val task = Task() 113 | 114 | private fun isCanceled() = task.isCanceled() 115 | 116 | /** 117 | * Suspends the coroutine call until [task] completes. 118 | * 119 | * @return the result of [task]. 120 | */ 121 | suspend fun await(task: Task, machine: Continuation) { 122 | if (isCanceled()) return 123 | this.task.awaitingOn(task) 124 | task.whenComplete( 125 | { result -> 126 | this.task.awaitDone() 127 | if (!isCanceled()) resume(machine, result) 128 | }, 129 | { throwable -> 130 | this.task.awaitDone() 131 | if (!isCanceled()) resumeWithException(machine, throwable) 132 | } 133 | ) 134 | } 135 | 136 | /** 137 | * Suspends the coroutine call until callee task completes. 138 | * 139 | * @return the result of the callee. 140 | */ 141 | suspend operator fun Task.getValue( 142 | thisRef: Any?, 143 | property: KProperty<*>, 144 | machine: Continuation 145 | ) { 146 | await(this, machine) 147 | } 148 | 149 | /** 150 | * For usage with Retrofit 2. 151 | * Enqueues [call] to be ran asynchronously and suspends the coroutine until [call] completes. 152 | * 153 | * @return the result of [call]. 154 | */ 155 | suspend fun await(call: Call, machine: Continuation>) { 156 | if (isCanceled()) return 157 | task.awaitingOn(CancelableCall(call)) 158 | call.enqueue( 159 | { response -> 160 | task.awaitDone() 161 | if (!isCanceled()) resume(machine, response) 162 | }, 163 | { throwable -> 164 | task.awaitDone() 165 | if (!isCanceled()) resumeWithException(machine, throwable) 166 | } 167 | ) 168 | } 169 | 170 | /** 171 | * For usage with Retrofit 2 172 | * Enqueues the callee Call to be ran asynchronously and suspends the coroutine until the callee completes. 173 | * 174 | * @return the result of the callee. 175 | */ 176 | suspend operator fun Call.getValue( 177 | thisRef: Any?, 178 | property: KProperty<*>, 179 | machine: Continuation> 180 | ) { 181 | await(this, machine) 182 | } 183 | 184 | /** 185 | * For usage with RxJava 1.x 186 | * Subscribes to the [single] and suspends the coroutine until [single] completes. 187 | * 188 | * @return the completed result of [single]. 189 | */ 190 | suspend fun await(single: Single1, machine: Continuation) { 191 | if (isCanceled()) return 192 | var subscription: Subscription1? = null 193 | 194 | task.awaitingOn(object : Cancelable { 195 | override fun cancel() { 196 | subscription?.unsubscribe() 197 | } 198 | 199 | override fun isCanceled(): Boolean { 200 | return subscription?.isUnsubscribed ?: false 201 | } 202 | }) 203 | 204 | subscription = single.subscribe( 205 | { result -> 206 | task.awaitDone() 207 | if (!isCanceled()) resume(machine, result) 208 | }, 209 | { throwable -> 210 | task.awaitDone() 211 | if (!isCanceled()) resumeWithException(machine, throwable) 212 | } 213 | ) 214 | } 215 | 216 | /** 217 | * For usage with RxJava 1.x 218 | * Subscribes to the callee [Single][rx.Single] and suspends the coroutine until the callee completes. 219 | * 220 | * @return the completed result of the callee [Single][rx.Single]. 221 | */ 222 | suspend operator fun Single1.getValue( 223 | thisRef: Any?, 224 | property: KProperty<*>, 225 | machine: Continuation 226 | ) { 227 | await(this, machine) 228 | } 229 | 230 | /** 231 | * For usage with RxJava 2.x 232 | * Subscribes to the [single] and suspends the coroutine until [single] completes. 233 | * 234 | * @return the completed result of [single]. 235 | */ 236 | suspend fun await(single: Single2, machine: Continuation) { 237 | if (isCanceled()) return 238 | var disposable: Disposable? = null 239 | 240 | task.awaitingOn(object : Cancelable { 241 | override fun cancel() { 242 | disposable?.dispose() 243 | } 244 | 245 | override fun isCanceled(): Boolean { 246 | return disposable?.isDisposed ?: false 247 | } 248 | }) 249 | 250 | disposable = single.subscribe( 251 | { result -> 252 | task.awaitDone() 253 | if (!isCanceled()) resume(machine, result) 254 | }, 255 | { throwable -> 256 | task.awaitDone() 257 | if (!isCanceled()) resumeWithException(machine, throwable) 258 | } 259 | ) 260 | } 261 | 262 | /** 263 | * For usage with RxJava 2.x 264 | * Subscribes to the callee [Single][io.reactivex.Single] and suspends the coroutine until the callee completes. 265 | * 266 | * @return the completed result of the callee [Single][io.reactivex.Single]. 267 | */ 268 | suspend operator fun Single2.getValue( 269 | thisRef: Any?, 270 | property: KProperty<*>, 271 | machine: Continuation 272 | ) { 273 | await(this, machine) 274 | } 275 | 276 | /** 277 | * Runs [f] asynchronously and suspends the coroutine call until [f] completes. 278 | * 279 | * @return the result of [f]. 280 | */ 281 | suspend fun await(f: () -> R, machine: Continuation) { 282 | if (isCanceled()) return 283 | task.startedWith(executorService.submit { 284 | try { 285 | val data = f() 286 | if (!isCanceled()) resume(machine, data) 287 | } catch(e: Throwable) { 288 | if (!isCanceled()) resumeWithException(machine, e) 289 | } 290 | }) 291 | } 292 | 293 | /** 294 | * Runs the callee function asynchronously and suspends the coroutine call until the function completes. 295 | * 296 | * @return the result of the callee function. 297 | */ 298 | suspend operator fun (() -> R).getValue( 299 | thisRef: Any?, 300 | property: KProperty<*>, 301 | machine: Continuation 302 | ) { 303 | await(this, machine) 304 | } 305 | 306 | private fun resume(machine: Continuation, result: R) { 307 | runOnUiIfNecessary { machine.resume(result) } 308 | } 309 | 310 | private fun resumeWithException(machine: Continuation, throwable: Throwable) { 311 | runOnUiIfNecessary { machine.resumeWithException(throwable) } 312 | } 313 | 314 | private fun runOnUiIfNecessary(action: () -> Unit) { 315 | if (returnToMainThread && Looper.myLooper() != Looper.getMainLooper()) { 316 | runOnUi(action) 317 | } else { 318 | action() 319 | } 320 | } 321 | 322 | @Suppress("unused", "unused_parameter") 323 | operator fun handleResult(value: T, c: Continuation) { 324 | task.complete(value) 325 | } 326 | 327 | @Suppress("unused", "unused_parameter") 328 | operator fun handleException(t: Throwable, c: Continuation) { 329 | if (isCanceled() && t is InterruptedException) return 330 | if (!task.handleError(t)) runOnUi { throw t } 331 | } 332 | } 333 | 334 | private val executorService by lazy { 335 | Executors.newCachedThreadPool() 336 | } 337 | -------------------------------------------------------------------------------- /asyncawait-android/src/main/kotlin/com/nhaarman/async/Cancelable.kt: -------------------------------------------------------------------------------- 1 | package com.nhaarman.async 2 | 3 | 4 | interface Cancelable { 5 | 6 | /** Cancels the [Cancelable]. */ 7 | fun cancel() 8 | 9 | /** Returns whether the [Cancelable] is canceled. */ 10 | fun isCanceled(): Boolean 11 | } 12 | 13 | internal class CancelableImpl : Cancelable { 14 | 15 | private @Volatile var canceled = false 16 | 17 | override fun cancel() { 18 | canceled = true 19 | } 20 | 21 | override fun isCanceled(): Boolean { 22 | return canceled 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /asyncawait-android/src/main/kotlin/com/nhaarman/async/CancelableCall.kt: -------------------------------------------------------------------------------- 1 | package com.nhaarman.async 2 | 3 | import retrofit2.Call 4 | import retrofit2.Callback 5 | import retrofit2.Response 6 | 7 | 8 | class CancelableCall( 9 | private val call: Call<*> 10 | ) : Cancelable { 11 | 12 | override fun cancel() { 13 | call.cancel() 14 | } 15 | 16 | override fun isCanceled(): Boolean { 17 | return call.isCanceled 18 | } 19 | } 20 | 21 | inline fun Call.enqueue( 22 | crossinline onResponse: (Response) -> Unit, 23 | crossinline onFailure: (Throwable) -> Unit 24 | ) = 25 | enqueue(object : Callback { 26 | override fun onResponse(call: Call, response: Response) { 27 | onResponse(response) 28 | } 29 | 30 | override fun onFailure(call: Call, t: Throwable) { 31 | onFailure(t) 32 | } 33 | }) 34 | -------------------------------------------------------------------------------- /asyncawait-android/src/main/kotlin/com/nhaarman/async/RunOnUi.kt: -------------------------------------------------------------------------------- 1 | package com.nhaarman.async 2 | 3 | import android.os.Handler 4 | import android.os.Looper 5 | import android.os.Message 6 | 7 | var uiRunner: UIRunner = HandlerUIRunner() 8 | 9 | internal fun runOnUi(action: () -> Unit) { 10 | uiRunner.runOnUi(action) 11 | } 12 | 13 | interface UIRunner { 14 | fun runOnUi(action: () -> Unit) 15 | } 16 | 17 | class SynchronousRunner : UIRunner { 18 | override fun runOnUi(action: () -> Unit) { 19 | action() 20 | } 21 | } 22 | 23 | class HandlerUIRunner : UIRunner { 24 | 25 | private val handler = object : Handler(Looper.getMainLooper()) { 26 | override fun handleMessage(msg: Message) { 27 | (msg.obj as? (() -> Unit))?.invoke() 28 | } 29 | } 30 | 31 | override fun runOnUi(action: () -> Unit) { 32 | handler.obtainMessage(0, action).sendToTarget() 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /asyncawait-android/src/main/kotlin/com/nhaarman/async/Task.kt: -------------------------------------------------------------------------------- 1 | package com.nhaarman.async 2 | 3 | import java.util.concurrent.CountDownLatch 4 | import java.util.concurrent.Future 5 | import java.util.concurrent.TimeUnit 6 | import java.util.concurrent.TimeoutException 7 | 8 | 9 | /** 10 | * A class that represents a cancelable task that can be awaited on. 11 | * When the task completes normally, an instance of type [T] is passed 12 | * as the result to the 'await' call. 13 | */ 14 | class Task( 15 | private val cancelable: Cancelable = CancelableImpl() 16 | ) : Cancelable by cancelable { 17 | 18 | /** The Future that was created to start the coroutine. */ 19 | private var runningTask: Future<*>? = null 20 | 21 | private @Volatile var onComplete: ((T) -> Unit)? = null 22 | private @Volatile var onError: ((Throwable) -> Unit)? = null 23 | 24 | private @Volatile var completedValue: CompletedValue? = null 25 | private @Volatile var erroredValue: Throwable? = null 26 | 27 | /** The task that we're currently awaiting on. */ 28 | private var current: Cancelable? = null 29 | 30 | internal fun awaitingOn(cancelable: Cancelable) { 31 | if (current != null) error("Already waiting on $current.") 32 | current = cancelable 33 | } 34 | 35 | internal fun awaitDone() { 36 | current = null 37 | } 38 | 39 | private val latch = CountDownLatch(1) 40 | 41 | internal fun whenComplete(onComplete: (T) -> Unit, onError: (Throwable) -> Unit) { 42 | this.onComplete = onComplete 43 | this.onError = onError 44 | 45 | completedValue?.let { onComplete(it.value) } 46 | erroredValue?.let { onError(it) } 47 | } 48 | 49 | internal fun startedWith(future: Future<*>) { 50 | runningTask = future 51 | } 52 | 53 | internal fun complete(value: T) { 54 | onComplete?.invoke(value) 55 | completedValue = CompletedValue(value) 56 | latch.countDown() 57 | } 58 | 59 | internal fun handleError(t: Throwable): Boolean { 60 | val result = onError?.invoke(t) != null 61 | erroredValue = t 62 | latch.countDown() 63 | return result 64 | } 65 | 66 | override fun cancel() { 67 | cancelable.cancel() 68 | 69 | current?.cancel() 70 | current = null 71 | 72 | runningTask?.cancel(true) 73 | runningTask = null 74 | 75 | onComplete = null 76 | onError = null 77 | } 78 | 79 | /** 80 | * Blocks the current thread until this task has completed 81 | * either successfully or unsuccessfully. 82 | * 83 | * @throws IllegalStateException if the task was already canceled. 84 | */ 85 | fun wait(): T { 86 | if (isCanceled()) throw IllegalStateException("Task is canceled.") 87 | latch.await() 88 | 89 | completedValue?.let { return it.value } 90 | erroredValue?.let { throw it } 91 | 92 | error("Neither completed nor errored value set.") 93 | } 94 | 95 | /** 96 | * Blocks the current thread until this task has completed 97 | * either successfully or unsuccessfully, or a timeout has passed. 98 | * 99 | * @param timeout the maximum time to wait 100 | * @param unit the time unit of [timeout] 101 | * 102 | * @throws TimeoutException if the timeout has passed before the task was completed. 103 | * @throws IllegalStateException if the task was already canceled. 104 | */ 105 | fun wait(timeout: Long, unit: TimeUnit): T { 106 | if (isCanceled()) throw IllegalStateException("Task is canceled.") 107 | 108 | latch.await(timeout, unit) 109 | 110 | if (latch.count > 0) throw TimeoutException() 111 | 112 | completedValue?.let { return it.value } 113 | erroredValue?.let { throw it } 114 | 115 | error("Neither completed nor errored value set.") 116 | } 117 | 118 | companion object { 119 | 120 | /** 121 | * Creates a [Task] that is completed with value [t]. 122 | */ 123 | @JvmStatic 124 | fun completed(t: T) = Task().apply { complete(t) } 125 | 126 | /** 127 | * Creates a [Task] that has errored with [t]. 128 | */ 129 | @JvmStatic 130 | fun errored(t: Throwable) = Task().apply { handleError(t) } 131 | } 132 | 133 | private class CompletedValue(val value: T) 134 | } 135 | -------------------------------------------------------------------------------- /asyncawait-android/src/test/kotlin/com/nhaarman/async/AsyncTest.kt: -------------------------------------------------------------------------------- 1 | package com.nhaarman.async 2 | 3 | import com.nhaarman.expect.expect 4 | import com.nhaarman.mockito_kotlin.* 5 | import io.reactivex.disposables.Disposable 6 | import org.junit.Before 7 | import org.junit.Test 8 | import retrofit2.Call 9 | import retrofit2.Callback 10 | import retrofit2.Response 11 | import rx.Subscription 12 | import java.util.concurrent.TimeUnit.MILLISECONDS 13 | import java.util.concurrent.TimeUnit.SECONDS 14 | import io.reactivex.Single as Single2 15 | import rx.Single as Single1 16 | 17 | @Suppress("IllegalIdentifier") 18 | class AsyncTest { 19 | 20 | private val resultString = "Result" 21 | 22 | private val mainThread = Thread.currentThread() 23 | 24 | @Before 25 | fun setup() { 26 | uiRunner = SynchronousRunner() 27 | } 28 | 29 | @Test 30 | fun `waiting on a directly terminating non-parameterized async returns the result`() { 31 | /* When */ 32 | val result = async { Unit }.testWait() 33 | 34 | /* Then */ 35 | expect(result).toBe(Unit) 36 | } 37 | 38 | @Test 39 | fun `waiting on a directly terminating async returns the result`() { 40 | /* When */ 41 | val result = async { resultString }.testWait() 42 | 43 | /* Then */ 44 | expect(result).toBe(resultString) 45 | } 46 | 47 | @Test 48 | fun `waiting on a task that directly completes with a null value`() { 49 | /* When */ 50 | val result = async { null }.testWait() 51 | 52 | /* Then */ 53 | expect(result).toBeNull() 54 | } 55 | 56 | @Test 57 | fun `waiting on an async that sleeps still returns the result`() { 58 | /* When */ 59 | val result = async { Thread.sleep(100); resultString }.testWait() 60 | 61 | /* Then */ 62 | expect(result).toBe(resultString) 63 | } 64 | 65 | @Test 66 | fun `waiting on a task that sleeps still returns the null value`() { 67 | /* When */ 68 | val result = async { Thread.sleep(100); null }.testWait() 69 | 70 | /* Then */ 71 | expect(result).toBeNull() 72 | } 73 | 74 | @Test 75 | fun `code executed in an async continues on mainthread until await`() { 76 | /* When */ 77 | val result = async { 78 | expect(Thread.currentThread()).toBeTheSameAs(mainThread) 79 | await { expect(Thread.currentThread().name).toContain("pool") } 80 | expect(Thread.currentThread().name).toContain("pool") 81 | 82 | resultString 83 | }.testWait() 84 | 85 | /* Then */ 86 | expect(result).toBe(resultString) 87 | } 88 | 89 | @Test(expected = IllegalStateException::class) 90 | fun `throwing an error synchronously inside async propagates`() { 91 | /* When */ 92 | async { 93 | error("Expected") 94 | } 95 | } 96 | 97 | @Test(expected = IllegalStateException::class) 98 | fun `throwing an error after await propagates when waited on`() { 99 | /* When */ 100 | async { 101 | await {} 102 | error("Expected") 103 | }.testWait() 104 | } 105 | 106 | @Test 107 | fun `catching an exception inside async does not propagate exception`() { 108 | /* When */ 109 | val result = async { 110 | try { 111 | await { error("Error") } 112 | } catch(e: IllegalStateException) { 113 | resultString 114 | } 115 | }.testWait() 116 | 117 | /* Then */ 118 | expect(result).toBe(resultString) 119 | } 120 | 121 | @Test 122 | fun `catching an exception outside async does not propagate exception`() { 123 | /* When */ 124 | val result = try { 125 | async { 126 | await { error("Error") } 127 | }.testWait() 128 | } catch(e: IllegalStateException) { 129 | resultString 130 | } 131 | 132 | /* Then */ 133 | expect(result).toBe(resultString) 134 | } 135 | 136 | @Test(expected = IllegalStateException::class) 137 | fun `waiting on an already canceled task throws an exception`() { 138 | /* Given */ 139 | val task = async { 140 | await { while (true); } 141 | resultString 142 | } 143 | task.cancel() 144 | 145 | /* When */ 146 | task.testWait() 147 | } 148 | 149 | @Test 150 | fun `awaiting on a task`() { 151 | /* When */ 152 | val result = async { 153 | await(async { resultString }) 154 | }.testWait() 155 | 156 | /* Then */ 157 | expect(result).toBe(resultString) 158 | } 159 | 160 | @Test(expected = IllegalStateException::class) 161 | fun `awaiting on a task that errors`() { 162 | /* When */ 163 | async { 164 | await(async { error("Expected") }) 165 | }.testWait() 166 | } 167 | 168 | @Test(expected = IllegalStateException::class) 169 | fun `awaiting on a task that errors asynchronously`() { 170 | /* When */ 171 | async { 172 | await(async { 173 | await { error("Expected") } 174 | }) 175 | }.testWait() 176 | } 177 | 178 | @Test 179 | fun `awaiting on a delegated task`() { 180 | /* When */ 181 | val result = async { 182 | val a by async { resultString } 183 | a 184 | }.testWait() 185 | 186 | /* Then */ 187 | expect(result).toBe(resultString) 188 | } 189 | 190 | @Test 191 | fun `awaiting on a delegated lambda`() { 192 | /* When */ 193 | val result = async { 194 | val a by { resultString } 195 | a 196 | }.testWait() 197 | 198 | /* Then */ 199 | expect(result).toBe(resultString) 200 | } 201 | 202 | @Test(expected = IllegalStateException::class) 203 | fun `awaiting on a delegated task that errors`() { 204 | /* When */ 205 | async { 206 | val a by async { error("Expected") } 207 | a 208 | }.testWait() 209 | } 210 | 211 | @Test 212 | fun `delegation evaluates in order`() { 213 | /* Given */ 214 | val a = mock<() -> Unit>() 215 | val b = mock<() -> Unit>() 216 | 217 | /* When */ 218 | async { 219 | val aResult by async { a() } 220 | val bResult by async { b() } 221 | 222 | bResult 223 | aResult 224 | } 225 | 226 | /* Then */ 227 | inOrder(a, b) { 228 | verify(a).invoke() 229 | verify(b).invoke() 230 | } 231 | } 232 | 233 | @Suppress("UNCHECKED_CAST") 234 | @Test 235 | fun `awaiting on a retrofit call`() { 236 | val call = mock>() 237 | whenever(call.enqueue(any())).then { 238 | (it.arguments[0] as Callback).onResponse(call, Response.success(resultString)) 239 | } 240 | 241 | /* When */ 242 | val result = async { 243 | await(call).body() 244 | }.testWait() 245 | 246 | /* Then */ 247 | expect(result).toBe(resultString) 248 | } 249 | 250 | @Test 251 | fun `canceling a retrofit call`() { 252 | /* Given */ 253 | val call = mock>() 254 | val task = async { 255 | await(call).body() 256 | } 257 | 258 | /* When */ 259 | task.cancel() 260 | 261 | /* Then */ 262 | verify(call).cancel() 263 | } 264 | 265 | @Suppress("UNCHECKED_CAST") 266 | @Test 267 | fun `awaiting on a delegated retrofit call`() { 268 | val call = mock>() 269 | whenever(call.enqueue(any())).then { 270 | (it.arguments[0] as Callback).onResponse(call, Response.success(resultString)) 271 | } 272 | 273 | /* When */ 274 | val result = async { 275 | val a by call 276 | a.body() 277 | }.testWait() 278 | 279 | /* Then */ 280 | expect(result).toBe(resultString) 281 | } 282 | 283 | @Test 284 | fun `awaiting on an RxJava1 Single`() { 285 | /* When */ 286 | val result = async { 287 | await(Single1.just(resultString)) 288 | }.testWait() 289 | 290 | /* Then */ 291 | expect(result).toBe(resultString) 292 | } 293 | 294 | @Test 295 | fun `canceling an RxJava1 Single`() { 296 | /* Given */ 297 | val subscription = mock() 298 | val single = mock> { 299 | on { subscribe(any(), any()) } doReturn subscription 300 | } 301 | 302 | val task = async { 303 | await(single) 304 | } 305 | 306 | /* When */ 307 | task.cancel() 308 | 309 | /* Then */ 310 | verify(subscription).unsubscribe() 311 | } 312 | 313 | @Test 314 | fun `awaiting on a delegated RxJava1 Single`() { 315 | /* When */ 316 | val result = async { 317 | val a by Single1.just(resultString) 318 | a 319 | }.testWait() 320 | 321 | /* Then */ 322 | expect(result).toBe(resultString) 323 | } 324 | 325 | @Test 326 | fun `awaiting on an RxJava2 Single`() { 327 | /* When */ 328 | val result = async { 329 | await(Single2.just(resultString)) 330 | }.testWait() 331 | 332 | /* Then */ 333 | expect(result).toBe(resultString) 334 | } 335 | 336 | @Test 337 | fun `canceling an RxJava2 Single`() { 338 | /* Given */ 339 | val disposable = mock() 340 | val single = mock> { 341 | on { subscribe(any(), any()) } doReturn disposable 342 | } 343 | 344 | val task = async { 345 | await(single) 346 | } 347 | 348 | /* When */ 349 | task.cancel() 350 | 351 | /* Then */ 352 | verify(disposable).dispose() 353 | } 354 | 355 | @Test 356 | fun `awaiting on a delegated RxJava2 Single`() { 357 | /* When */ 358 | val result = async { 359 | val a by Single2.just(resultString) 360 | a 361 | }.testWait() 362 | 363 | /* Then */ 364 | expect(result).toBe(resultString) 365 | } 366 | 367 | @Test 368 | fun delay() { 369 | /* Given */ 370 | val start = System.currentTimeMillis() 371 | 372 | /* When */ 373 | delay(100, MILLISECONDS).testWait() 374 | 375 | /* Then */ 376 | expect(System.currentTimeMillis() - start).toBeGreaterThan(99) 377 | } 378 | 379 | @Test 380 | fun completedTask() { 381 | /* Given */ 382 | val task = Task.completed(resultString) 383 | 384 | /* When */ 385 | val result = task.testWait() 386 | 387 | /* Then */ 388 | expect(result).toBe(resultString) 389 | } 390 | 391 | @Test(expected = UnsupportedOperationException::class) 392 | fun erroredTask() { 393 | /* Given */ 394 | val task = Task.errored(UnsupportedOperationException()) 395 | 396 | /* When */ 397 | task.testWait() 398 | } 399 | } 400 | 401 | private fun Task.testWait() = wait(1, SECONDS) -------------------------------------------------------------------------------- /asyncawait-android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker: -------------------------------------------------------------------------------- 1 | mock-maker-inline -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | apply from: './dependencies.gradle' 3 | 4 | repositories { 5 | jcenter() 6 | mavenCentral() 7 | maven { url 'https://dl.bintray.com/kotlin/kotlin-eap-1.1/' } 8 | } 9 | 10 | dependencies { 11 | classpath androidBuildTools 12 | classpath gradleVersionsPlugin 13 | classpath kotlinGradlePlugin 14 | classpath dokkaGradlePlugin 15 | classpath gradleBintrayPlugin 16 | classpath androidMavenPlugin 17 | } 18 | } 19 | 20 | apply plugin: 'com.github.ben-manes.versions' 21 | project.apply from: './dependencies.gradle' 22 | apply from: 'gradle/scripts/tagging.gradle' 23 | 24 | subprojects { 25 | buildscript { 26 | repositories { 27 | jcenter() 28 | mavenCentral() 29 | maven { url 'https://dl.bintray.com/kotlin/kotlin-eap-1.1/' } 30 | } 31 | } 32 | 33 | repositories { 34 | maven { url 'https://dl.bintray.com/kotlin/kotlin-eap-1.1' } 35 | jcenter() 36 | mavenCentral() 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /dependencies.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | kotlinVersion = "1.1-M03" 3 | 4 | kotlinGradlePlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 5 | kotlinStdLib = "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 6 | 7 | androidBuildTools = "com.android.tools.build:gradle:2.2.2" 8 | androidMavenPlugin = "com.github.dcendents:android-maven-gradle-plugin:1.5" 9 | dokkaGradlePlugin = "org.jetbrains.dokka:dokka-gradle-plugin:0.9.9" 10 | gradleBintrayPlugin = "com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3" 11 | gradleVersionsPlugin = "com.github.ben-manes:gradle-versions-plugin:0.13.0" 12 | 13 | retrofit2 = "com.squareup.retrofit2:retrofit:2.1.0" 14 | rxJava1 = "io.reactivex:rxjava:1.2.3" 15 | rxJava2 = "io.reactivex.rxjava2:rxjava:2.0.1" 16 | 17 | androidSupportTestRunner = "com.android.support.test:runner:0.5" 18 | androidSupportTestRules = "com.android.support.test:rules:0.5" 19 | expectKt = "com.nhaarman:expect.kt:0.6.0" 20 | junit = "junit:junit:4.12" 21 | mockitoKotlin = "com.nhaarman:mockito-kotlin:0.12.2" 22 | } 23 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | isRelease=false -------------------------------------------------------------------------------- /gradle/scripts/publishing.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'signing' 2 | apply plugin: 'com.jfrog.bintray' 3 | apply plugin: 'com.github.dcendents.android-maven' 4 | 5 | group = 'com.nhaarman' 6 | version = rootProject.ext.versionName 7 | def sonatypeUsername = hasProperty('sonatype_username') ? sonatype_username : System.getenv('SONATYPE_USERNAME') 8 | def sonatypePassword = hasProperty('sonatype_password') ? sonatype_password : System.getenv('SONATYPE_PASSWORD') 9 | 10 | 11 | task javadocJar(type: Jar, dependsOn: dokka) { 12 | classifier = 'javadoc' 13 | from 'build/javadoc' 14 | } 15 | 16 | task sourcesJar(type: Jar) { 17 | from android.sourceSets.main.java.srcDirs 18 | classifier = 'sources' 19 | } 20 | 21 | artifacts { 22 | archives javadocJar 23 | archives sourcesJar 24 | } 25 | 26 | signing { 27 | sign configurations.archives 28 | } 29 | 30 | install { 31 | repositories.mavenInstaller { 32 | pom { 33 | project { 34 | name 'AsyncAwait-Android' 35 | packaging 'aar' 36 | description 'Async-Await in Android' 37 | url 'https://github.com/nhaarman/asyncawait-android' 38 | 39 | scm { 40 | url 'scm:git@github.com:nhaarman/asyncawait-android.git' 41 | connection 'scm:git@github.com:nhaarman/asyncawait-android.git' 42 | developerConnection 'scm:git@github.com:nhaarman/asyncawait-android.git' 43 | } 44 | 45 | licenses { 46 | license { 47 | name 'Apache 2.0' 48 | distribution 'repo' 49 | } 50 | } 51 | 52 | developers { 53 | developer { 54 | id 'nhaarman' 55 | name 'Niek Haarman' 56 | } 57 | } 58 | } 59 | } 60 | } 61 | } 62 | 63 | bintray { 64 | user = hasProperty('bintray_username') ? bintray_username : System.getenv('BINTRAY_USER') 65 | key = hasProperty('bintray_key') ? bintray_key : System.getenv('BINTRAY_KEY') 66 | 67 | configurations = ['archives'] 68 | 69 | publish = true 70 | 71 | pkg { 72 | repo = 'maven' 73 | name = 'AsyncAwait-Android' 74 | licenses = ['Apache-2.0'] 75 | vcsUrl = 'https://github.com/nhaarman/AsyncAwait-Android.git' 76 | 77 | version { 78 | name = versionName 79 | 80 | gpg { 81 | sign = true 82 | } 83 | 84 | mavenCentralSync { 85 | sync = true 86 | user = hasProperty('sonatype_username') ? sonatype_username : System.getenv('SONATYPE_USERNAME') 87 | password = hasProperty('sonatype_password') ? sonatype_password : System.getenv('SONATYPE_PASSWORD') 88 | close = '1' 89 | } 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /gradle/scripts/tagging.gradle: -------------------------------------------------------------------------------- 1 | new ByteArrayOutputStream().withStream { os -> 2 | 3 | exec { 4 | commandLine 'git', 'describe' 5 | standardOutput = os 6 | } 7 | 8 | String tag = os.toString().trim(); 9 | if (tag.length() == 0) { 10 | tag = "0.0.0" 11 | } else if (tag.indexOf('-') != -1 && tag.length() > tag.indexOf('-') + 1 && tag.charAt(tag.indexOf('-') + 1).isDigit()) { 12 | tag = tag.substring(0, tag.indexOf('-')); 13 | } 14 | 15 | ext.versionName = tag; 16 | 17 | if (isRelease == 'false') { 18 | int lastNumber = Integer.parseInt(tag.substring(tag.size() - 1)) 19 | ext.versionName = tag.substring(0, tag.size() - 1) + (lastNumber + 1) + "-SNAPSHOT"; 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nhaarman/AsyncAwait-Android/d3edba9c53fb73511c6a5118bba2e4736bb3e2f5/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.2-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':asyncawait-android' 2 | --------------------------------------------------------------------------------