├── .github ├── release-drafter.yml └── workflows │ ├── android.yml │ └── release-management.yml ├── .gitignore ├── LICENSE ├── README.md ├── autodispose ├── .gitignore ├── build.gradle ├── gradle.properties ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── github │ │ │ └── satoshun │ │ │ └── coroutine │ │ │ └── autodispose │ │ │ ├── lifecycle │ │ │ ├── LifecycleAutoDisposeInterceptor.kt │ │ │ ├── LifecycleFinishedException.kt │ │ │ └── LifecycleJob.kt │ │ │ └── view │ │ │ ├── View.kt │ │ │ ├── ViewAutoDisposeInterceptor.kt │ │ │ └── ViewJob.kt │ └── res │ │ └── values │ │ ├── ids.xml │ │ └── strings.xml │ └── test │ ├── AndroidManifest.xml │ └── java │ └── com │ └── github │ └── satoshun │ └── coroutine │ └── autodispose │ ├── lifecycle │ ├── JobSubject.kt │ ├── LifecycleAutoDisposeInterceptorTest.kt │ ├── LifecycleAutoDisposeScopeTest.kt │ ├── LifecycleOwnerJobTest.kt │ └── TestActivity.kt │ └── view │ ├── ViewAutoDisposeInterceptorTest.kt │ ├── ViewJobTest.kt │ └── ViewTest.kt ├── build.gradle ├── buildSrc ├── build.gradle.kts └── src │ └── main │ └── kotlin │ └── dependencies │ └── Dependencies.kt ├── debug.keystore ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── github │ │ └── satoshun │ │ └── coroutine │ │ └── autodispose │ │ └── sample │ │ ├── MainActivity.kt │ │ ├── MainFragment.kt │ │ └── MainView.kt │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ ├── main_act.xml │ └── main_frag.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | name-template: 'v$NEXT_PATCH_VERSION' 2 | tag-template: 'v$NEXT_PATCH_VERSION' 3 | template: | 4 | $CHANGES 5 | -------------------------------------------------------------------------------- /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v2 14 | 15 | - name: set up JDK 1.8 16 | uses: actions/setup-java@v2 17 | with: 18 | distribution: 'zulu' 19 | java-version: '8' 20 | 21 | - uses: actions/cache@v2 22 | with: 23 | path: ~/.gradle/caches 24 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/Dependencies.kt') }} 25 | restore-keys: | 26 | ${{ runner.os }}-gradle- 27 | 28 | - name: Test with Gradle 29 | run: ./gradlew test --stacktrace 30 | -------------------------------------------------------------------------------- /.github/workflows/release-management.yml: -------------------------------------------------------------------------------- 1 | name: Release Drafter 2 | 3 | on: 4 | push: 5 | # branches to consider in the event; optional, defaults to all 6 | branches: 7 | - master 8 | 9 | jobs: 10 | update_release_draft: 11 | runs-on: ubuntu-latest 12 | steps: 13 | # Drafts your next Release notes as Pull Requests are merged into "master" 14 | - uses: release-drafter/release-drafter@v5.3.0 15 | env: 16 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches/build_file_checksums.ser 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | .DS_Store 9 | /build 10 | /captures 11 | .externalNativeBuild 12 | -------------------------------------------------------------------------------- /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. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coroutine AutoDispose 2 | 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.satoshun.coroutine.autodispose/autodispose/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.satoshun.coroutine.autodispose/autodispose) 4 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-CoroutineAutoDispose-green.svg?style=flat)](https://android-arsenal.com/details/1/7406) 5 | 6 | Coroutine AutoDispose is an Kotlin Coroutine library for automatically disposal. 7 | 8 | ## Overview 9 | 10 | Often, Coroutine subscriptions need to stop in response to some event (like a Activity#onStop()). 11 | In order to support this common scenario in Coroutine. 12 | 13 | ### autoDisposeScope 14 | 15 | This library provide a autoDisposeScope extension method. 16 | It can be used like a [lifecycleScope](https://developer.android.com/reference/kotlin/androidx/lifecycle/package-summary#(androidx.lifecycle.LifecycleOwner).lifecycleScope:androidx.lifecycle.LifecycleCoroutineScope). 17 | 18 | It create a [CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/) for automatically disposal with Android Architecture Component Lifecycle events. 19 | 20 | ```kotlin 21 | class MainActivity : AppCompatActivity() { 22 | override fun onCreate(savedInstanceState: Bundle?) { 23 | // automatically dispose when onDestroy 24 | autoDisposeScope.launch { 25 | ... 26 | } 27 | } 28 | 29 | override fun onResume() { 30 | // automatically dispose when onPause 31 | autoDisposeScope.launch { 32 | ... 33 | } 34 | } 35 | } 36 | ``` 37 | 38 | It can also be uses with Fragment and View. 39 | 40 | ### Lifecycle.autoDispose(Job) 41 | 42 | This Job an automatically disposal with Android Lifecycle events. 43 | 44 | ```kotlin 45 | val job = launch { ... } 46 | lifecycle.autoDispose(job) 47 | ``` 48 | 49 | ### Use with RecyclerView 50 | 51 | CoroutineScope can be used from a itemView of RecyclerView.ViewHolder. 52 | 53 | ```kotlin 54 | override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { 55 | holder.itemView.autoDisposeScope.launch { 56 | ... 57 | } 58 | } 59 | ``` 60 | 61 | ## Download 62 | 63 | ```groovy 64 | implementation 'com.github.satoshun.coroutine.autodispose:autodispose:${version}' 65 | ``` 66 | 67 | ## etc 68 | 69 | This library referred [uber/AutoDispose](https://github.com/uber/AutoDispose). 70 | -------------------------------------------------------------------------------- /autodispose/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /autodispose/build.gradle: -------------------------------------------------------------------------------- 1 | import static dependencies.DependenciesKt.* 2 | 3 | apply plugin: 'com.android.library' 4 | apply plugin: 'kotlin-android' 5 | apply plugin: "com.vanniktech.maven.publish" 6 | 7 | android { 8 | compileSdkVersion COMPILE_SDK 9 | 10 | defaultConfig { 11 | minSdkVersion MIN_SDK 12 | } 13 | 14 | buildTypes { 15 | debug { 16 | testCoverageEnabled true 17 | } 18 | } 19 | compileOptions { 20 | sourceCompatibility JavaVersion.VERSION_1_8 21 | targetCompatibility JavaVersion.VERSION_1_8 22 | } 23 | } 24 | 25 | dependencies { 26 | api KOTLIN 27 | 28 | api COROUTINE 29 | api LIFECYCLE 30 | api LIFECYCLE_RUNTIME 31 | 32 | testImplementation JUNIT 33 | testImplementation TRUTH 34 | testImplementation TEST_RULES 35 | testImplementation TEST_RUNNER 36 | testImplementation TEST_CORE 37 | testImplementation TEST_JUNIT_RULES 38 | testImplementation ROBOLECTRIC 39 | testImplementation ACTIVITYX 40 | } 41 | -------------------------------------------------------------------------------- /autodispose/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_ARTIFACT_ID=autodispose 2 | POM_NAME=Corouotine Autodispose 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /autodispose/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /autodispose/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /autodispose/src/main/java/com/github/satoshun/coroutine/autodispose/lifecycle/LifecycleAutoDisposeInterceptor.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.lifecycle 2 | 3 | import androidx.lifecycle.Lifecycle 4 | import androidx.lifecycle.LifecycleOwner 5 | import androidx.lifecycle.lifecycleScope 6 | import kotlinx.coroutines.CoroutineScope 7 | import kotlinx.coroutines.Job 8 | import kotlinx.coroutines.plus 9 | import kotlin.coroutines.Continuation 10 | import kotlin.coroutines.ContinuationInterceptor 11 | import kotlin.coroutines.CoroutineContext 12 | 13 | /** 14 | * Create a [ContinuationInterceptor] that follows lifecycle of LifecycleOwner. 15 | */ 16 | fun LifecycleOwner.autoDisposeInterceptor(): ContinuationInterceptor = 17 | LifecycleAutoDisposeInterceptor(this) 18 | 19 | /** 20 | * Create a [ContinuationInterceptor] that follows lifecycle of LifecycleOwner. 21 | */ 22 | @Suppress("FunctionName") 23 | fun LifecycleAutoDisposeInterceptor(lifecycleOwner: LifecycleOwner): ContinuationInterceptor = 24 | LifecycleAutoDisposeInterceptor(lifecycleOwner.lifecycle) 25 | 26 | /** 27 | * Create a [ContinuationInterceptor] that follows lifecycle. 28 | */ 29 | fun Lifecycle.autoDisposeInterceptor(): ContinuationInterceptor = 30 | LifecycleAutoDisposeInterceptor(this) 31 | 32 | /** 33 | * Create a [ContinuationInterceptor] that follows lifecycle. 34 | */ 35 | @Suppress("FunctionName") 36 | fun LifecycleAutoDisposeInterceptor(lifecycle: Lifecycle): ContinuationInterceptor = 37 | LifecycleAutoDisposeInterceptorImpl(lifecycle) 38 | 39 | /** 40 | * * Create a [CoroutineScope] from [androidx.lifecycle.lifecycleScope] that follows lifecycle. 41 | */ 42 | val LifecycleOwner.autoDisposeScope: CoroutineScope 43 | get() = lifecycleScope + LifecycleAutoDisposeInterceptor(this) 44 | 45 | private class LifecycleAutoDisposeInterceptorImpl( 46 | private val lifecycle: Lifecycle 47 | ) : ContinuationInterceptor { 48 | override val key: CoroutineContext.Key<*> 49 | get() = ContinuationInterceptor 50 | 51 | override fun interceptContinuation(continuation: Continuation): Continuation { 52 | val job = continuation.context[Job] 53 | if (job != null) { 54 | lifecycle.autoDispose(job) 55 | } 56 | return continuation 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /autodispose/src/main/java/com/github/satoshun/coroutine/autodispose/lifecycle/LifecycleFinishedException.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.lifecycle 2 | 3 | class LifecycleFinishedException(message: String) : RuntimeException(message) 4 | -------------------------------------------------------------------------------- /autodispose/src/main/java/com/github/satoshun/coroutine/autodispose/lifecycle/LifecycleJob.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.lifecycle 2 | 3 | import androidx.lifecycle.Lifecycle 4 | import androidx.lifecycle.LifecycleObserver 5 | import androidx.lifecycle.LifecycleOwner 6 | import androidx.lifecycle.OnLifecycleEvent 7 | import androidx.lifecycle.coroutineScope 8 | import kotlinx.coroutines.CompletionHandler 9 | import kotlinx.coroutines.Dispatchers 10 | import kotlinx.coroutines.Job 11 | import kotlinx.coroutines.launch 12 | import kotlinx.coroutines.withContext 13 | 14 | /** 15 | * [Job] is automatically disposed and follows the lifecycle of LifecycleOwner. 16 | * 17 | * @throws LifecycleFinishedException when lifecycle of LifecycleOwner is destroy 18 | */ 19 | fun LifecycleOwner.autoDispose(job: Job): LifecycleObserver { 20 | return lifecycle.autoDispose(job) 21 | } 22 | 23 | /** 24 | * [Job] is automatically disposed and follows the lifecycle. 25 | * 26 | * @throws LifecycleFinishedException when lifecycle is destroy 27 | */ 28 | fun Lifecycle.autoDispose(job: Job): LifecycleObserver { 29 | val event = when (this.currentState) { 30 | Lifecycle.State.INITIALIZED -> Lifecycle.Event.ON_DESTROY 31 | Lifecycle.State.CREATED -> Lifecycle.Event.ON_DESTROY 32 | Lifecycle.State.STARTED -> Lifecycle.Event.ON_STOP 33 | Lifecycle.State.RESUMED -> Lifecycle.Event.ON_PAUSE 34 | Lifecycle.State.DESTROYED -> throw LifecycleFinishedException("finished lifecycle") 35 | } 36 | val observer = LifecycleJobObserver(job, event, this) 37 | this.addObserver(observer) 38 | job.invokeOnCompletion(observer) 39 | return observer 40 | } 41 | 42 | private class LifecycleJobObserver( 43 | private val job: Job, 44 | private val target: Lifecycle.Event, 45 | private val lifecycle: Lifecycle 46 | ) : LifecycleObserver, CompletionHandler { 47 | @OnLifecycleEvent(Lifecycle.Event.ON_ANY) 48 | fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) { 49 | if (event == this.target) { 50 | owner.lifecycle.removeObserver(this) 51 | job.cancel() 52 | } 53 | } 54 | 55 | override fun invoke(cause: Throwable?) { 56 | lifecycle.coroutineScope.launch { 57 | withContext(Dispatchers.Main.immediate) { 58 | lifecycle.removeObserver(this@LifecycleJobObserver) 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /autodispose/src/main/java/com/github/satoshun/coroutine/autodispose/view/View.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.view 2 | 3 | import android.view.View 4 | import com.github.satoshun.coroutine.autodispose.R 5 | import kotlinx.coroutines.CoroutineScope 6 | import kotlinx.coroutines.Dispatchers 7 | import kotlinx.coroutines.SupervisorJob 8 | import kotlin.coroutines.CoroutineContext 9 | 10 | private val TAG = R.id.autodispose_view_tag 11 | 12 | /** 13 | * [CoroutineScope] tied to this [View] 14 | * 15 | * This scope will be canceled when View is detached. 16 | */ 17 | val View.autoDisposeScope: CoroutineScope 18 | get() { 19 | val exist = getTag(TAG) as? CoroutineScope 20 | if (exist != null) { 21 | return exist 22 | } 23 | val newScope = ViewCoroutineScope( 24 | SupervisorJob() + 25 | Dispatchers.Main + 26 | autoDisposeInterceptor() 27 | ) 28 | setTag(TAG, newScope) 29 | return newScope 30 | } 31 | 32 | internal class ViewCoroutineScope( 33 | override val coroutineContext: CoroutineContext 34 | ) : CoroutineScope 35 | -------------------------------------------------------------------------------- /autodispose/src/main/java/com/github/satoshun/coroutine/autodispose/view/ViewAutoDisposeInterceptor.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.view 2 | 3 | import android.view.View 4 | import kotlinx.coroutines.Job 5 | import kotlin.coroutines.Continuation 6 | import kotlin.coroutines.ContinuationInterceptor 7 | import kotlin.coroutines.CoroutineContext 8 | 9 | /** 10 | * Create a ContinuationInterceptor that follows attach/detach lifecycle of [View]. 11 | */ 12 | @Suppress("FunctionName") 13 | fun ViewAutoDisposeInterceptor(view: View): ContinuationInterceptor = 14 | ViewAutoDisposeInterceptorImpl(view) 15 | 16 | /** 17 | * Create a ContinuationInterceptor that follows attach/detach lifecycle of [View]. 18 | */ 19 | fun View.autoDisposeInterceptor(): ContinuationInterceptor = 20 | ViewAutoDisposeInterceptor(this) 21 | 22 | private class ViewAutoDisposeInterceptorImpl( 23 | private val view: View 24 | ) : ContinuationInterceptor { 25 | override val key: CoroutineContext.Key<*> 26 | get() = ContinuationInterceptor 27 | 28 | override fun interceptContinuation(continuation: Continuation): Continuation { 29 | val job = continuation.context[Job] 30 | if (job != null) { 31 | view.autoDispose(job) 32 | } 33 | return continuation 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /autodispose/src/main/java/com/github/satoshun/coroutine/autodispose/view/ViewJob.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.view 2 | 3 | import android.view.View 4 | import kotlinx.coroutines.CompletionHandler 5 | import kotlinx.coroutines.Job 6 | 7 | /** 8 | * [Job] is automatically disposed and follows the attach/detach lifecycle of [View]. 9 | */ 10 | fun View.autoDispose(job: Job) { 11 | val listener = ViewListener(this, job) 12 | this.addOnAttachStateChangeListener(listener) 13 | } 14 | 15 | private class ViewListener( 16 | private val view: View, 17 | private val job: Job 18 | ) : View.OnAttachStateChangeListener, 19 | CompletionHandler { 20 | override fun onViewDetachedFromWindow(v: View) { 21 | view.removeOnAttachStateChangeListener(this) 22 | job.cancel() 23 | } 24 | 25 | override fun onViewAttachedToWindow(v: View) { 26 | // do nothing 27 | } 28 | 29 | override fun invoke(cause: Throwable?) { 30 | view.removeOnAttachStateChangeListener(this) 31 | job.cancel() 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /autodispose/src/main/res/values/ids.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /autodispose/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | autodispose 3 | 4 | -------------------------------------------------------------------------------- /autodispose/src/test/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /autodispose/src/test/java/com/github/satoshun/coroutine/autodispose/lifecycle/JobSubject.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.lifecycle 2 | 3 | import com.google.common.truth.Fact.simpleFact 4 | import com.google.common.truth.FailureMetadata 5 | import com.google.common.truth.Subject 6 | import com.google.common.truth.Truth 7 | import kotlinx.coroutines.Job 8 | 9 | class JobSubject( 10 | metadata: FailureMetadata?, 11 | private val actual: Job? 12 | ) : Subject(metadata, actual) { 13 | companion object { 14 | fun assertThat(job: Job?): JobSubject { 15 | return Truth.assertAbout(::JobSubject).that(job) 16 | } 17 | } 18 | 19 | fun isCanceled() { 20 | Truth.assertThat(actual).isNotNull() 21 | if (!actual!!.isCancelled) { 22 | failWithoutActual(simpleFact("not canceled Job")) 23 | } 24 | } 25 | 26 | fun isNotCanceled() { 27 | Truth.assertThat(actual).isNotNull() 28 | if (actual!!.isCancelled) { 29 | failWithoutActual(simpleFact("already canceled Job")) 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /autodispose/src/test/java/com/github/satoshun/coroutine/autodispose/lifecycle/LifecycleAutoDisposeInterceptorTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.lifecycle 2 | 3 | import androidx.lifecycle.Lifecycle 4 | import androidx.lifecycle.LifecycleRegistry 5 | import androidx.test.ext.junit.rules.ActivityScenarioRule 6 | import androidx.test.ext.junit.runners.AndroidJUnit4 7 | import kotlinx.coroutines.Job 8 | import kotlinx.coroutines.async 9 | import kotlinx.coroutines.delay 10 | import kotlinx.coroutines.launch 11 | import org.junit.Rule 12 | import org.junit.Test 13 | import org.junit.runner.RunWith 14 | 15 | @RunWith(AndroidJUnit4::class) 16 | class LifecycleAutoDisposeInterceptorTest { 17 | @get:Rule val activity = ActivityScenarioRule(TestActivity::class.java) 18 | 19 | @Test 20 | fun lifecycleAutoDisposeInterceptor_onCreated() { 21 | val scenario = activity.scenario 22 | 23 | scenario.moveToState(Lifecycle.State.CREATED) 24 | var job: Job? = null 25 | scenario.onActivity { 26 | job = it.launch { 27 | delay(10000) 28 | } 29 | } 30 | JobSubject.assertThat(job).isNotCanceled() 31 | 32 | scenario.onActivity { 33 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) 34 | } 35 | JobSubject.assertThat(job).isNotCanceled() 36 | 37 | scenario.moveToState(Lifecycle.State.DESTROYED) 38 | JobSubject.assertThat(job).isCanceled() 39 | } 40 | 41 | @Test 42 | fun lifecycleAutoDisposeInterceptor_onResumed() { 43 | val scenario = activity.scenario 44 | 45 | scenario.moveToState(Lifecycle.State.RESUMED) 46 | var job: Job? = null 47 | scenario.onActivity { 48 | job = it.launch { 49 | delay(10000) 50 | } 51 | } 52 | JobSubject.assertThat(job).isNotCanceled() 53 | scenario.onActivity { 54 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) 55 | } 56 | 57 | JobSubject.assertThat(job).isCanceled() 58 | } 59 | 60 | @Test 61 | fun lifecycleAutoDisposeInterceptor_nested() { 62 | val scenario = activity.scenario 63 | 64 | scenario.moveToState(Lifecycle.State.CREATED) 65 | var parentJob: Job? = null 66 | var nestedJob1: Job? = null 67 | var nestedJob2: Job? = null 68 | scenario.onActivity { 69 | parentJob = it.launch { 70 | nestedJob1 = launch { delay(10000) } 71 | nestedJob2 = async { delay(10000) } 72 | delay(10000) 73 | } 74 | } 75 | 76 | 77 | JobSubject.assertThat(parentJob).isNotCanceled() 78 | JobSubject.assertThat(nestedJob1).isNotCanceled() 79 | JobSubject.assertThat(nestedJob2).isNotCanceled() 80 | 81 | scenario.onActivity { 82 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) 83 | } 84 | JobSubject.assertThat(parentJob).isNotCanceled() 85 | JobSubject.assertThat(nestedJob1).isNotCanceled() 86 | JobSubject.assertThat(nestedJob2).isNotCanceled() 87 | 88 | nestedJob2!!.cancel() 89 | JobSubject.assertThat(parentJob).isNotCanceled() 90 | JobSubject.assertThat(nestedJob1).isNotCanceled() 91 | JobSubject.assertThat(nestedJob2).isCanceled() 92 | 93 | scenario.moveToState(Lifecycle.State.DESTROYED) 94 | JobSubject.assertThat(parentJob).isCanceled() 95 | JobSubject.assertThat(nestedJob1).isCanceled() 96 | JobSubject.assertThat(nestedJob2).isCanceled() 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /autodispose/src/test/java/com/github/satoshun/coroutine/autodispose/lifecycle/LifecycleAutoDisposeScopeTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.lifecycle 2 | 3 | import androidx.lifecycle.Lifecycle 4 | import androidx.lifecycle.LifecycleRegistry 5 | import androidx.test.ext.junit.rules.ActivityScenarioRule 6 | import androidx.test.ext.junit.runners.AndroidJUnit4 7 | import kotlinx.coroutines.Job 8 | import kotlinx.coroutines.delay 9 | import kotlinx.coroutines.launch 10 | import org.junit.Rule 11 | import org.junit.Test 12 | import org.junit.runner.RunWith 13 | 14 | @RunWith(AndroidJUnit4::class) 15 | class LifecycleAutoDisposeScopeTest { 16 | @get:Rule val activity = ActivityScenarioRule(AutoDisposeScopeTestActivity::class.java) 17 | 18 | @Test 19 | fun autoDisposeScope_Created_to_Destroy() { 20 | val scenario = activity.scenario 21 | 22 | scenario.moveToState(Lifecycle.State.CREATED) 23 | 24 | var job1: Job? = null 25 | scenario.onActivity { 26 | job1 = it.autoDisposeScope.launch { delay(Long.MAX_VALUE) } 27 | } 28 | var job2: Job? = null 29 | scenario.onActivity { 30 | job2 = it.autoDisposeScope.launch { delay(Long.MAX_VALUE) } 31 | } 32 | JobSubject.assertThat(job1).isNotCanceled() 33 | JobSubject.assertThat(job2).isNotCanceled() 34 | 35 | scenario.moveToState(Lifecycle.State.RESUMED) 36 | JobSubject.assertThat(job1).isNotCanceled() 37 | JobSubject.assertThat(job2).isNotCanceled() 38 | 39 | scenario.onActivity { 40 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) 41 | } 42 | JobSubject.assertThat(job1).isNotCanceled() 43 | JobSubject.assertThat(job2).isNotCanceled() 44 | 45 | scenario.moveToState(Lifecycle.State.DESTROYED) 46 | JobSubject.assertThat(job1).isCanceled() 47 | JobSubject.assertThat(job2).isCanceled() 48 | } 49 | 50 | @Test 51 | fun autoDisposeScope_Resume_to_Pause() { 52 | val scenario = activity.scenario 53 | 54 | scenario.moveToState(Lifecycle.State.RESUMED) 55 | 56 | var job1: Job? = null 57 | scenario.onActivity { 58 | job1 = it.autoDisposeScope.launch { delay(Long.MAX_VALUE) } 59 | } 60 | var job2: Job? = null 61 | scenario.onActivity { 62 | job2 = it.autoDisposeScope.launch { delay(Long.MAX_VALUE) } 63 | } 64 | JobSubject.assertThat(job1).isNotCanceled() 65 | JobSubject.assertThat(job2).isNotCanceled() 66 | 67 | scenario.onActivity { 68 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) 69 | } 70 | JobSubject.assertThat(job1).isCanceled() 71 | JobSubject.assertThat(job2).isCanceled() 72 | 73 | scenario.moveToState(Lifecycle.State.DESTROYED) 74 | JobSubject.assertThat(job1).isCanceled() 75 | JobSubject.assertThat(job2).isCanceled() 76 | } 77 | 78 | @Test 79 | fun autoDisposeScope_Start_to_Stop() { 80 | val scenario = activity.scenario 81 | 82 | scenario.moveToState(Lifecycle.State.STARTED) 83 | 84 | var job1: Job? = null 85 | scenario.onActivity { 86 | job1 = it.autoDisposeScope.launch { delay(Long.MAX_VALUE) } 87 | } 88 | var job2: Job? = null 89 | scenario.onActivity { 90 | job2 = it.autoDisposeScope.launch { delay(Long.MAX_VALUE) } 91 | } 92 | JobSubject.assertThat(job1).isNotCanceled() 93 | JobSubject.assertThat(job2).isNotCanceled() 94 | 95 | scenario.onActivity { 96 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) 97 | } 98 | JobSubject.assertThat(job1).isNotCanceled() 99 | JobSubject.assertThat(job2).isNotCanceled() 100 | 101 | scenario.onActivity { 102 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_STOP) 103 | } 104 | JobSubject.assertThat(job1).isCanceled() 105 | JobSubject.assertThat(job2).isCanceled() 106 | 107 | scenario.moveToState(Lifecycle.State.DESTROYED) 108 | JobSubject.assertThat(job1).isCanceled() 109 | JobSubject.assertThat(job2).isCanceled() 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /autodispose/src/test/java/com/github/satoshun/coroutine/autodispose/lifecycle/LifecycleOwnerJobTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.lifecycle 2 | 3 | import androidx.lifecycle.Lifecycle 4 | import androidx.lifecycle.LifecycleObserver 5 | import androidx.lifecycle.LifecycleRegistry 6 | import androidx.test.ext.junit.rules.ActivityScenarioRule 7 | import androidx.test.ext.junit.runners.AndroidJUnit4 8 | import com.google.common.truth.Truth.assertThat 9 | import kotlinx.coroutines.GlobalScope 10 | import kotlinx.coroutines.cancelAndJoin 11 | import kotlinx.coroutines.delay 12 | import kotlinx.coroutines.launch 13 | import kotlinx.coroutines.runBlocking 14 | import org.junit.Rule 15 | import org.junit.Test 16 | import org.junit.runner.RunWith 17 | 18 | @RunWith(AndroidJUnit4::class) 19 | class LifecycleOwnerJobTest { 20 | @get:Rule val scenarioRule = ActivityScenarioRule(TestActivity::class.java) 21 | 22 | @Test 23 | fun addJob_onCreated() { 24 | val job = GlobalScope.launch { delay(100000) } 25 | 26 | val scenario = scenarioRule.scenario 27 | 28 | scenario.moveToState(Lifecycle.State.CREATED) 29 | scenario.onActivity { 30 | it.autoDispose(job) 31 | } 32 | JobSubject.assertThat(job).isNotCanceled() 33 | 34 | scenario.moveToState(Lifecycle.State.RESUMED) 35 | JobSubject.assertThat(job).isNotCanceled() 36 | 37 | scenario.onActivity { 38 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) 39 | } 40 | JobSubject.assertThat(job).isNotCanceled() 41 | 42 | scenario.moveToState(Lifecycle.State.DESTROYED) 43 | JobSubject.assertThat(job).isCanceled() 44 | } 45 | 46 | @Test 47 | fun addJob_onResumed() { 48 | val job = GlobalScope.launch { delay(100000) } 49 | 50 | val scenario = scenarioRule.scenario 51 | 52 | scenario.moveToState(Lifecycle.State.RESUMED) 53 | scenario.onActivity { 54 | it.autoDispose(job) 55 | } 56 | JobSubject.assertThat(job).isNotCanceled() 57 | 58 | scenario.onActivity { 59 | (it.lifecycle as LifecycleRegistry).handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) 60 | } 61 | JobSubject.assertThat(job).isCanceled() 62 | } 63 | 64 | @Test 65 | fun addJob_onDestroyed() { 66 | val job = GlobalScope.launch { delay(100000) } 67 | 68 | val lifecycle = object : Lifecycle() { 69 | override fun addObserver(observer: LifecycleObserver) { 70 | } 71 | 72 | override fun removeObserver(observer: LifecycleObserver) { 73 | } 74 | 75 | override fun getCurrentState(): State { 76 | return State.DESTROYED 77 | } 78 | } 79 | 80 | val result = runCatching { lifecycle.autoDispose(job) } 81 | assertThat(result.exceptionOrNull()).isInstanceOf(LifecycleFinishedException::class.java) 82 | } 83 | 84 | @Test 85 | fun completionHandler() { 86 | val job = GlobalScope.launch { delay(100000) } 87 | 88 | val scenario = scenarioRule.scenario 89 | scenario.moveToState(Lifecycle.State.CREATED) 90 | 91 | var observer: LifecycleObserver? = null 92 | scenario.onActivity { observer = it.autoDispose(job) } 93 | 94 | runBlocking { job.cancelAndJoin() } 95 | 96 | scenario.onActivity { 97 | val count = (it.lifecycle as LifecycleRegistry).observerCount 98 | 99 | // already removed when job canceled(completed) 100 | it.lifecycle.removeObserver(observer!!) 101 | 102 | assertThat((it.lifecycle as LifecycleRegistry).observerCount) 103 | .isEqualTo(count) 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /autodispose/src/test/java/com/github/satoshun/coroutine/autodispose/lifecycle/TestActivity.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.lifecycle 2 | 3 | import androidx.activity.ComponentActivity 4 | import kotlinx.coroutines.CoroutineScope 5 | import kotlinx.coroutines.Dispatchers 6 | import kotlin.coroutines.CoroutineContext 7 | 8 | class TestActivity : ComponentActivity(), CoroutineScope { 9 | override val coroutineContext: CoroutineContext 10 | get() = Dispatchers.Main + autoDisposeInterceptor() 11 | } 12 | 13 | class AutoDisposeScopeTestActivity : ComponentActivity() 14 | -------------------------------------------------------------------------------- /autodispose/src/test/java/com/github/satoshun/coroutine/autodispose/view/ViewAutoDisposeInterceptorTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.view 2 | 3 | import android.content.Context 4 | import android.view.View 5 | import android.view.ViewGroup 6 | import androidx.activity.ComponentActivity 7 | import androidx.lifecycle.Lifecycle 8 | import androidx.test.ext.junit.rules.ActivityScenarioRule 9 | import androidx.test.ext.junit.runners.AndroidJUnit4 10 | import com.github.satoshun.coroutine.autodispose.lifecycle.JobSubject 11 | import kotlinx.coroutines.CoroutineScope 12 | import kotlinx.coroutines.Dispatchers 13 | import kotlinx.coroutines.Job 14 | import kotlinx.coroutines.delay 15 | import kotlinx.coroutines.launch 16 | import org.junit.Rule 17 | import org.junit.Test 18 | import org.junit.runner.RunWith 19 | import kotlin.coroutines.CoroutineContext 20 | 21 | @RunWith(AndroidJUnit4::class) 22 | class ViewAutoDisposeInterceptorTest { 23 | @get:Rule val scenarioRule = ActivityScenarioRule(ComponentActivity::class.java) 24 | 25 | @Test 26 | fun viewAutoDisposeInterceptor() { 27 | val scenario = scenarioRule.scenario 28 | 29 | var job: Job? = null 30 | var view: TestView? = null 31 | scenario.moveToState(Lifecycle.State.CREATED) 32 | scenario.onActivity { 33 | view = TestView(it) 34 | it.setContentView(view) 35 | 36 | job = view!!.launch { delay(100000) } 37 | } 38 | JobSubject.assertThat(job).isNotCanceled() 39 | 40 | scenario.onActivity { 41 | // detach view 42 | it.findViewById(android.R.id.content).removeView(view) 43 | } 44 | JobSubject.assertThat(job).isCanceled() 45 | } 46 | 47 | @Test 48 | fun viewAutoDisposeInterceptor_parentJob_cancel() { 49 | val scenario = scenarioRule.scenario 50 | 51 | var job: Job? = null 52 | var view: TestView? = null 53 | scenario.moveToState(Lifecycle.State.CREATED) 54 | scenario.onActivity { 55 | view = TestView(it) 56 | it.setContentView(view) 57 | 58 | job = view!!.launch { delay(100000) } 59 | } 60 | JobSubject.assertThat(job).isNotCanceled() 61 | 62 | view!!.job.cancel() 63 | JobSubject.assertThat(job).isCanceled() 64 | } 65 | } 66 | 67 | class TestView(context: Context) : View(context), CoroutineScope { 68 | val job = Job() 69 | override val coroutineContext: CoroutineContext 70 | get() = job + Dispatchers.Main + ViewAutoDisposeInterceptor(this) 71 | } 72 | -------------------------------------------------------------------------------- /autodispose/src/test/java/com/github/satoshun/coroutine/autodispose/view/ViewJobTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.view 2 | 3 | import android.view.View 4 | import android.view.ViewGroup 5 | import android.widget.TextView 6 | import androidx.activity.ComponentActivity 7 | import androidx.lifecycle.Lifecycle 8 | import androidx.test.ext.junit.rules.ActivityScenarioRule 9 | import androidx.test.ext.junit.runners.AndroidJUnit4 10 | import com.github.satoshun.coroutine.autodispose.lifecycle.JobSubject 11 | import kotlinx.coroutines.GlobalScope 12 | import kotlinx.coroutines.delay 13 | import kotlinx.coroutines.launch 14 | import org.junit.Rule 15 | import org.junit.Test 16 | import org.junit.runner.RunWith 17 | 18 | @RunWith(AndroidJUnit4::class) 19 | class ViewJobTest { 20 | @get:Rule val scenarioRule = ActivityScenarioRule(ComponentActivity::class.java) 21 | 22 | @Test 23 | fun addJob_detached() { 24 | val job = GlobalScope.launch { delay(10000) } 25 | val scenario = scenarioRule.scenario 26 | 27 | var view: View? = null 28 | scenario.moveToState(Lifecycle.State.CREATED) 29 | scenario.onActivity { 30 | view = TextView(it) 31 | it.setContentView(view) 32 | 33 | view!!.autoDispose(job) 34 | } 35 | JobSubject.assertThat(job).isNotCanceled() 36 | 37 | scenario.onActivity { 38 | // detach view 39 | it.findViewById(android.R.id.content).removeView(view) 40 | } 41 | JobSubject.assertThat(job).isCanceled() 42 | } 43 | 44 | @Test 45 | fun addJob_cancel() { 46 | val job = GlobalScope.launch { delay(10000) } 47 | val scenario = scenarioRule.scenario 48 | 49 | scenario.moveToState(Lifecycle.State.CREATED) 50 | scenario.onActivity { 51 | val view = TextView(it) 52 | it.setContentView(view) 53 | 54 | view.autoDispose(job) 55 | } 56 | JobSubject.assertThat(job).isNotCanceled() 57 | 58 | job.cancel() 59 | JobSubject.assertThat(job).isCanceled() 60 | 61 | // todo check is called View.removeOnAttachStateChangeListener 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /autodispose/src/test/java/com/github/satoshun/coroutine/autodispose/view/ViewTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.view 2 | 3 | import android.app.Activity 4 | import android.view.View 5 | import android.view.ViewGroup 6 | import androidx.activity.ComponentActivity 7 | import androidx.test.ext.junit.rules.ActivityScenarioRule 8 | import androidx.test.ext.junit.runners.AndroidJUnit4 9 | import com.github.satoshun.coroutine.autodispose.lifecycle.JobSubject 10 | import com.google.common.truth.Truth.assertThat 11 | import kotlinx.coroutines.delay 12 | import kotlinx.coroutines.launch 13 | import org.junit.Rule 14 | import org.junit.Test 15 | import org.junit.runner.RunWith 16 | 17 | @RunWith(AndroidJUnit4::class) 18 | class ViewTest { 19 | @get:Rule val scenarioRule = ActivityScenarioRule(ComponentActivity::class.java) 20 | 21 | private val Activity.contentView get() = findViewById(android.R.id.content) 22 | 23 | @Test 24 | fun `cancel job when view is detached`() { 25 | scenarioRule.scenario.onActivity { 26 | val view = View(it) 27 | it.contentView.addView(view) 28 | 29 | // simulate too too long task 30 | val job = view.autoDisposeScope.launch { delay(1000000) } 31 | 32 | JobSubject.assertThat(job).isNotCanceled() 33 | 34 | it.contentView.removeView(view) 35 | 36 | JobSubject.assertThat(job).isCanceled() 37 | } 38 | } 39 | 40 | @Test 41 | fun `cancel job`() { 42 | scenarioRule.scenario.onActivity { 43 | val view = View(it) 44 | it.contentView.addView(view) 45 | 46 | // simulate too too long task 47 | val job = view.autoDisposeScope.launch { delay(1000000) } 48 | JobSubject.assertThat(job).isNotCanceled() 49 | 50 | job.cancel() 51 | JobSubject.assertThat(job).isCanceled() 52 | 53 | it.contentView.removeView(view) 54 | JobSubject.assertThat(job).isCanceled() 55 | } 56 | } 57 | 58 | @Test 59 | fun `multi subscribe`() { 60 | scenarioRule.scenario.onActivity { 61 | val view = View(it) 62 | it.contentView.addView(view) 63 | 64 | // simulate too too long task 65 | val job1 = view.autoDisposeScope.launch { delay(1000000) } 66 | JobSubject.assertThat(job1).isNotCanceled() 67 | job1.cancel() 68 | JobSubject.assertThat(job1).isCanceled() 69 | 70 | val job2 = view.autoDisposeScope.launch { delay(1000000) } 71 | JobSubject.assertThat(job2).isNotCanceled() 72 | job2.cancel() 73 | JobSubject.assertThat(job2).isCanceled() 74 | 75 | // same coroutine scope 76 | assertThat(view.autoDisposeScope).isSameInstanceAs(view.autoDisposeScope) 77 | 78 | it.contentView.removeView(view) 79 | JobSubject.assertThat(job1).isCanceled() 80 | JobSubject.assertThat(job2).isCanceled() 81 | } 82 | } 83 | 84 | @Test 85 | fun `view is attach and detach`() { 86 | scenarioRule.scenario.onActivity { 87 | val view = View(it) 88 | it.contentView.addView(view) 89 | 90 | // simulate too too long task 91 | val job1 = view.autoDisposeScope.launch { delay(1000000) } 92 | JobSubject.assertThat(job1).isNotCanceled() 93 | 94 | it.contentView.removeView(view) 95 | JobSubject.assertThat(job1).isCanceled() 96 | 97 | val job2 = view.autoDisposeScope.launch { delay(1000000) } 98 | JobSubject.assertThat(job2).isNotCanceled() 99 | 100 | it.contentView.addView(view) 101 | JobSubject.assertThat(job2).isNotCanceled() 102 | 103 | val job3 = view.autoDisposeScope.launch { delay(1000000) } 104 | JobSubject.assertThat(job3).isNotCanceled() 105 | 106 | it.contentView.removeView(view) 107 | JobSubject.assertThat(job2).isCanceled() 108 | JobSubject.assertThat(job3).isCanceled() 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | import static dependencies.DependenciesKt.* 2 | 3 | buildscript { 4 | repositories { 5 | google() 6 | jcenter() 7 | } 8 | 9 | dependencies { 10 | classpath ANDROID_PLUGIN 11 | classpath KOTLIN_PLUGIN 12 | classpath PUBLISH_PLUGIN 13 | } 14 | } 15 | 16 | allprojects { 17 | repositories { 18 | google() 19 | jcenter() 20 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" } 21 | } 22 | 23 | tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { 24 | kotlinOptions { 25 | jvmTarget = JavaVersion.VERSION_1_8 26 | } 27 | } 28 | } 29 | 30 | task clean(type: Delete) { 31 | delete rootProject.buildDir 32 | } 33 | -------------------------------------------------------------------------------- /buildSrc/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `kotlin-dsl` 3 | } 4 | 5 | apply { 6 | plugin("kotlin") 7 | } 8 | 9 | repositories { 10 | jcenter() 11 | google() 12 | } 13 | 14 | dependencies { 15 | implementation(gradleApi()) 16 | } 17 | -------------------------------------------------------------------------------- /buildSrc/src/main/kotlin/dependencies/Dependencies.kt: -------------------------------------------------------------------------------- 1 | package dependencies 2 | 3 | const val COMPILE_SDK = 30 4 | const val MIN_SDK = 14 5 | const val TARGET_SDK = 30 6 | 7 | const val VKOTLIN = "1.4.32" 8 | 9 | const val ANDROID_PLUGIN = "com.android.tools.build:gradle:4.2.1" 10 | const val KOTLIN_PLUGIN = "org.jetbrains.kotlin:kotlin-gradle-plugin:$VKOTLIN" 11 | const val PUBLISH_PLUGIN = "com.vanniktech:gradle-maven-publish-plugin:0.15.1" 12 | 13 | private const val VCOUROUTINE = "1.4.3" 14 | const val KOTLIN = "org.jetbrains.kotlin:kotlin-stdlib:$VKOTLIN" 15 | const val COROUTINE = "org.jetbrains.kotlinx:kotlinx-coroutines-core:$VCOUROUTINE" 16 | const val UI_COROUTINE = "org.jetbrains.kotlinx:kotlinx-coroutines-android:$VCOUROUTINE" 17 | 18 | private const val VLIFECYCLE = "2.3.1" 19 | const val LIFECYCLE = "androidx.lifecycle:lifecycle-common:$VLIFECYCLE" 20 | const val LIFECYCLE_RUNTIME = "androidx.lifecycle:lifecycle-runtime-ktx:$VLIFECYCLE" 21 | 22 | // use from sample 23 | const val APPCOMPAT = "androidx.appcompat:appcompat:1.1.0" 24 | const val CONSTRAINTLAYOUT = "androidx.constraintlayout:constraintlayout:2.0.4" 25 | const val RECYCLER_VIEW = "androidx.recyclerview:recyclerview:1.0.0" 26 | const val FRAGMENTX = "androidx.fragment:fragment-ktx:1.2.0" 27 | const val KTX = "androidx.core:core-ktx:1.1.0" 28 | 29 | // use from test 30 | const val JUNIT = "junit:junit:4.12" 31 | const val TRUTH = "com.google.truth:truth:1.0" 32 | const val TEST_RULES = "androidx.test:rules:1.1.1" 33 | const val TEST_RUNNER = "androidx.test:runner:1.1.1" 34 | const val TEST_CORE = "androidx.test:core-ktx:1.1.0" 35 | const val TEST_JUNIT_RULES = "androidx.test.ext:junit-ktx:1.1.0" 36 | const val ESPRESSO = "androidx.test.espresso:espresso-core:3.1.1" 37 | const val ROBOLECTRIC = "org.robolectric:robolectric:4.1" 38 | const val ACTIVITYX = "androidx.activity:activity-ktx:1.1.0" 39 | -------------------------------------------------------------------------------- /debug.keystore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/debug.keystore -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | GROUP=com.github.satoshun.coroutine.autodispose 2 | VERSION_NAME=0.3.1 3 | 4 | POM_DESCRIPTION=Coroutine AutoDispose is an Kotlin Coroutine library for automatically disposal 5 | 6 | POM_URL=https://github.com/satoshun/CoroutineAutoDispose 7 | POM_SCM_URL=https://github.com/satoshun/CoroutineAutoDispose 8 | POM_SCM_CONNECTION=scm:git:git://github.com/satoshun/CoroutineAutoDispose.git 9 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/satoshun/CoroutineAutoDispose.git 10 | 11 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 12 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 13 | POM_LICENCE_DIST=repo 14 | 15 | POM_DEVELOPER_ID=satoshun 16 | POM_DEVELOPER_NAME=Sato Shun 17 | 18 | android.useAndroidX=true 19 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or 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 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /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 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | 88 | @rem Execute Gradle 89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 90 | 91 | :end 92 | @rem End local scope for the variables with windows NT shell 93 | if "%ERRORLEVEL%"=="0" goto mainEnd 94 | 95 | :fail 96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 97 | rem the _cmd.exe /c_ return code! 98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 99 | exit /b 1 100 | 101 | :mainEnd 102 | if "%OS%"=="Windows_NT" endlocal 103 | 104 | :omega 105 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | import static dependencies.DependenciesKt.* 2 | 3 | apply plugin: 'com.android.application' 4 | apply plugin: 'kotlin-android' 5 | 6 | android { 7 | compileSdkVersion COMPILE_SDK 8 | 9 | defaultConfig { 10 | applicationId "com.github.satoshun.coroutine.autodispose.sample" 11 | 12 | minSdkVersion MIN_SDK 13 | targetSdkVersion TARGET_SDK 14 | versionCode 1 15 | versionName "1.0" 16 | } 17 | 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | signingConfig signingConfigs.debug 22 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | 26 | signingConfigs { 27 | debug { 28 | storeFile rootProject.file('debug.keystore') 29 | keyAlias 'androiddebugkey' 30 | keyPassword 'android' 31 | storePassword 'android' 32 | } 33 | } 34 | 35 | compileOptions { 36 | sourceCompatibility JavaVersion.VERSION_1_8 37 | targetCompatibility JavaVersion.VERSION_1_8 38 | } 39 | } 40 | 41 | dependencies { 42 | implementation project(':autodispose') 43 | // implementation 'com.github.satoshun.coroutine.autodispose:autodispose:0.2.0' 44 | 45 | implementation KOTLIN 46 | 47 | implementation CONSTRAINTLAYOUT 48 | implementation RECYCLER_VIEW 49 | 50 | implementation APPCOMPAT 51 | implementation KTX 52 | implementation ACTIVITYX 53 | implementation FRAGMENTX 54 | 55 | implementation LIFECYCLE_RUNTIME 56 | 57 | implementation COROUTINE 58 | implementation UI_COROUTINE 59 | } 60 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /sample/src/main/java/com/github/satoshun/coroutine/autodispose/sample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.sample 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import android.view.ViewGroup 6 | import android.widget.TextView 7 | import androidx.appcompat.app.AppCompatActivity 8 | import androidx.fragment.app.commit 9 | import androidx.recyclerview.widget.LinearLayoutManager 10 | import androidx.recyclerview.widget.RecyclerView 11 | import com.github.satoshun.coroutine.autodispose.lifecycle.autoDisposeScope 12 | import com.github.satoshun.coroutine.autodispose.view.autoDisposeScope 13 | import kotlinx.coroutines.delay 14 | import kotlinx.coroutines.launch 15 | 16 | class MainActivity : AppCompatActivity () { 17 | override fun onCreate(savedInstanceState: Bundle?) { 18 | super.onCreate(savedInstanceState) 19 | setContentView(R.layout.main_act) 20 | 21 | // auto dispose when onDestroy 22 | val childJob = autoDisposeScope.launch { 23 | while (true) { 24 | delay(1000) 25 | Log.d("MainActivity", "onCreate loop") 26 | } 27 | } 28 | childJob.invokeOnCompletion { 29 | Log.d("MainActivity", "onCreate completed") 30 | } 31 | 32 | supportFragmentManager.commit { 33 | add(R.id.frame, MainFragment()) 34 | } 35 | 36 | findViewById(R.id.root).addView(MainView(this)) 37 | 38 | val recycler = findViewById(R.id.recycler) 39 | recycler.adapter = SampleAdapter() 40 | recycler.layoutManager = LinearLayoutManager(this) 41 | } 42 | 43 | override fun onResume() { 44 | super.onResume() 45 | // auto dispose when onPause 46 | val childJob = autoDisposeScope.launch { 47 | while (true) { 48 | delay(3000) 49 | Log.d("MainActivity", "onResume loop") 50 | } 51 | } 52 | childJob.invokeOnCompletion { 53 | Log.d("MainActivity", "onResume completed") 54 | } 55 | } 56 | } 57 | 58 | internal class SampleAdapter : RecyclerView.Adapter() { 59 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = 60 | object : RecyclerView.ViewHolder( 61 | TextView(parent.context) 62 | ) {} 63 | 64 | override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { 65 | (holder.itemView as TextView).text = position.toString() 66 | 67 | val job = holder.itemView.autoDisposeScope.launch { 68 | delay(3000) 69 | Log.d("RecyclerView", "success $position") 70 | } 71 | job.invokeOnCompletion { 72 | Log.d("RecyclerView", "complete $position") 73 | } 74 | } 75 | 76 | override fun getItemCount(): Int = 1000 77 | } 78 | -------------------------------------------------------------------------------- /sample/src/main/java/com/github/satoshun/coroutine/autodispose/sample/MainFragment.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.sample 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import android.view.LayoutInflater 6 | import android.view.View 7 | import android.view.ViewGroup 8 | import android.widget.TextView 9 | import androidx.fragment.app.Fragment 10 | import com.github.satoshun.coroutine.autodispose.lifecycle.autoDisposeScope 11 | import kotlinx.coroutines.delay 12 | import kotlinx.coroutines.launch 13 | 14 | class MainFragment : Fragment() { 15 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { 16 | return TextView(context) 17 | } 18 | 19 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 20 | super.onViewCreated(view, savedInstanceState) 21 | 22 | // auto release when onDestroyView 23 | val job = autoDisposeScope.launch { 24 | while (true) { 25 | delay(3000) 26 | Log.d("MainFragment", "onViewCreated loop") 27 | } 28 | } 29 | job.invokeOnCompletion { 30 | Log.d("MainFragment", "onViewCreated completed") 31 | } 32 | } 33 | 34 | override fun onResume() { 35 | super.onResume() 36 | // auto release when onPause 37 | val job = autoDisposeScope.launch { 38 | while (true) { 39 | delay(3000) 40 | Log.d("MainFragment", "onResume loop") 41 | } 42 | } 43 | job.invokeOnCompletion { 44 | Log.d("MainFragment", "onResume completed") 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /sample/src/main/java/com/github/satoshun/coroutine/autodispose/sample/MainView.kt: -------------------------------------------------------------------------------- 1 | package com.github.satoshun.coroutine.autodispose.sample 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import android.view.View 6 | import com.github.satoshun.coroutine.autodispose.view.autoDisposeScope 7 | import kotlinx.coroutines.delay 8 | import kotlinx.coroutines.launch 9 | 10 | class MainView(context: Context) : View(context) { 11 | init { 12 | val job = autoDisposeScope.launch { 13 | while (true) { 14 | delay(1000) 15 | Log.d("MainView", "init loop") 16 | } 17 | } 18 | job.invokeOnCompletion { 19 | Log.d("MainView", "init completed") 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/main_act.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 17 | 18 | 26 | 27 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/main_frag.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | 17 | 18 | 22 | 23 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/satoshun/CoroutineAutoDispose/f15695a259a596bc2e7a7fb82f12adbbbcbc17b7/sample/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Coroutine AutoDispose 3 | 4 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':sample' 2 | include ':autodispose' 3 | --------------------------------------------------------------------------------