Repository: trello-archive/RxLifecycle Branch: master Commit: 0dabd1c4322e Files: 99 Total size: 234.0 KB Directory structure: gitextract_s0_yo6v8/ ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle/ │ ├── artifacts.gradle │ ├── gradle-mvn-push.gradle │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── rxlifecycle/ │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── trello/ │ │ └── rxlifecycle4/ │ │ ├── Functions.java │ │ ├── LifecycleProvider.java │ │ ├── LifecycleTransformer.java │ │ ├── OutsideLifecycleException.java │ │ ├── RxLifecycle.java │ │ └── internal/ │ │ └── Preconditions.java │ └── test/ │ └── java/ │ └── com/ │ └── trello/ │ └── rxlifecycle4/ │ ├── OutsideLifecycleExceptionTest.java │ ├── RxLifecycleTest.java │ ├── UntilCorrespondingEventTransformerCompletableTest.java │ ├── UntilCorrespondingEventTransformerFlowableTest.java │ ├── UntilCorrespondingEventTransformerMaybeTest.java │ ├── UntilCorrespondingEventTransformerObservableTest.java │ ├── UntilCorrespondingEventTransformerSingleTest.java │ ├── UntilEventTransformerCompletableTest.java │ ├── UntilEventTransformerFlowableTest.java │ ├── UntilEventTransformerMaybeTest.java │ ├── UntilEventTransformerObservableTest.java │ ├── UntilEventTransformerSingleTest.java │ ├── UntilLifecycleTransformerCompletableTest.java │ ├── UntilLifecycleTransformerFlowableTest.java │ ├── UntilLifecycleTransformerMaybeTest.java │ ├── UntilLifecycleTransformerObservableTest.java │ └── UntilLifecycleTransformerSingleTest.java ├── rxlifecycle-android/ │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── trello/ │ │ └── rxlifecycle4/ │ │ └── android/ │ │ ├── ActivityEvent.java │ │ ├── FragmentEvent.java │ │ ├── RxLifecycleAndroid.java │ │ └── ViewDetachesOnSubscribe.java │ └── test/ │ └── java/ │ └── com/ │ └── trello/ │ └── rxlifecycle4/ │ ├── RxLifecycleTest.java │ └── TestUtil.java ├── rxlifecycle-android-lifecycle/ │ ├── .gitignore │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── trello/ │ │ └── lifecycle4/ │ │ └── android/ │ │ └── lifecycle/ │ │ ├── AndroidLifecycle.java │ │ └── RxLifecycleAndroidLifecycle.java │ └── test/ │ └── java/ │ └── com/ │ └── trello/ │ └── rxlifecycle4/ │ ├── RxLifecycleTest.java │ └── android/ │ └── lifecycle/ │ ├── AndroidLifecycleActivityTest.java │ └── AndroidLifecycleFragmentTest.java ├── rxlifecycle-android-lifecycle-kotlin/ │ ├── .gitignore │ ├── build.gradle │ ├── gradle.properties │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── trello/ │ │ └── rxlifecycle4/ │ │ └── android/ │ │ └── lifecycle/ │ │ └── kotlin/ │ │ └── rxlifecycle.kt │ └── res/ │ └── values/ │ └── strings.xml ├── rxlifecycle-components/ │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── trello/ │ │ └── rxlifecycle4/ │ │ └── components/ │ │ ├── RxActivity.java │ │ ├── RxDialogFragment.java │ │ ├── RxFragment.java │ │ ├── RxPreferenceFragment.java │ │ └── support/ │ │ ├── RxAppCompatActivity.java │ │ ├── RxAppCompatDialogFragment.java │ │ ├── RxDialogFragment.java │ │ ├── RxFragment.java │ │ └── RxFragmentActivity.java │ └── test/ │ └── java/ │ └── com/ │ └── trello/ │ └── rxlifecycle4/ │ └── components/ │ ├── RxActivityLifecycleTest.java │ ├── RxFragmentLifecycleTest.java │ └── support/ │ └── RxSupportFragmentLifecycleTest.java ├── rxlifecycle-components-preference/ │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── trello/ │ │ └── rxlifecycle4/ │ │ └── components/ │ │ └── preference/ │ │ ├── RxEditTextPreferenceDialogFragmentCompat.java │ │ ├── RxListPreferenceDialogFragmentCompat.java │ │ ├── RxPreferenceDialogFragmentCompat.java │ │ └── RxPreferenceFragmentCompat.java │ └── test/ │ └── java/ │ └── com/ │ └── trello/ │ └── rxlifecycle4/ │ └── components/ │ └── preference/ │ └── RxPreferenceFragmentLifecycleTest.java ├── rxlifecycle-kotlin/ │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ └── java/ │ └── com/ │ └── trello/ │ └── rxlifecycle4/ │ └── kotlin/ │ └── rxlifecycle.kt ├── rxlifecycle-sample/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── trello/ │ │ └── rxlifecycle4/ │ │ └── sample/ │ │ └── MainActivity.java │ ├── kotlin/ │ │ └── com/ │ │ └── trello/ │ │ └── rxlifecycle4/ │ │ └── sample/ │ │ └── KotlinActivity.kt │ └── res/ │ ├── layout/ │ │ └── activity_main.xml │ └── values/ │ ├── dimens.xml │ └── strings.xml └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Built application files *.apk *.ap_ # Files for the Dalvik VM *.dex # Java class files *.class # Generated files bin/ gen/ # Gradle files .gradle/ build/ /*/build/ # Local configuration file (sdk path, etc) local.properties # Proguard folder generated by Eclipse proguard/ # Log Files *.log # IntelliJ .idea/ *.iml ================================================ FILE: .travis.yml ================================================ language: android android: components: - tools - platform-tools - build-tools-28.0.3 - android-28 - extra-android-m2repository jdk: oraclejdk8 notifications: email: false sudo: false cache: directories: - $HOME/.gradle script: ./gradlew build test ================================================ FILE: CHANGELOG.md ================================================ # Changelog ## 4.0.2 (2020-11-05) - [#332](https://github.com/trello/RxLifecycle/pull/332): Namespace Kotlin module names ## 4.0.1 (2020-10-29) - [#330](https://github.com/trello/RxLifecycle/pull/330): Corrected package name in rxlifecycle-android-lifecycle-kotlin ## 4.0.0 (2020-05-23) This major revision was made to support RxJava 3. RxLifecycle 4.0 lives in a new namespace and package names so that it can work side-by-side with previous versions of RxLifecycle. - [#317](https://github.com/trello/RxLifecycle/pull/317): Upgrade to RxJava 3 - [#319](https://github.com/trello/RxLifecycle/pull/319): Updated namespace to com.trello.rxlifecycle4 ## 3.1.0 (2019-09-21) - [#290](https://github.com/trello/RxLifecycle/pull/290): Fixed up some missing rxlifecycle3 conversions - [#308](https://github.com/trello/RxLifecycle/pull/308): Support LayoutId constructors for AppCompatActivity and (AndroidX)Fragment ## 3.0.0 (2018-10-25) - [#285](https://github.com/trello/RxLifecycle/pull/285): Updated base package to com.trello.rxlifecycle3 - [#284](https://github.com/trello/RxLifecycle/pull/284): Deprecate rxlifecycle-navi - [#283](https://github.com/trello/RxLifecycle/pull/283): Upgraded to AndroidX ## 2.2.2 (2018-07-29) - [#275](https://github.com/trello/RxLifecycle/pull/275): Updated dependencies Normally simply updating dependencies wouldn't justify a new release, except that there are some R8 issues with RxLifecycle (due to it being compiled with Android lifecycle 1.0.0 instead of 1.1.0). ## 2.2.1 (2017-11-15) - [#248](https://github.com/trello/RxLifecycle/pull/248): Remove generic type declaration for Completable bindings - [#249](https://github.com/trello/RxLifecycle/pull/249): Updated to release version of Android architecture components ## 2.2.0 (2017-09-06) - [#239](https://github.com/trello/RxLifecycle/pull/239): Added support for support preference fragments These can be found in the new rxlifecycle-components-preference artifact. ## 2.1.0 (2017-05-27) - [#216](https://github.com/trello/RxLifecycle/pull/216): Added support for Android Architecture Components These can be found in the new rxlifecycle-android-lifecycle and rxlifecycle-android-kotlin artifacts. - [#219](https://github.com/trello/RxLifecycle/pull/219): Fix potential build issues by making JSR305 compileOnly ## 2.0.1 (2016-11-23) - [#183](https://github.com/trello/RxLifecycle/pull/183): Fix usage of null in navi module ## 2.0 (2016-11-21) This major revision was made to support RxJava 2. RxLifecycle 2.0 lives in a new namespace and package names so that it can work side-by-side with RxLifecycle 1.0 (while transitioning). The biggest change is that `LifecycleTransformer` now works for *all* RxJava types: `Observable`, `Flowable`, `Single`, `Maybe` and `Completable`. Unlike before, there's no extra steps you have to take to make it work with types other than `Observable`. - [#167](https://github.com/trello/RxLifecycle/pull/167): Upgrade to RxJava 2 - [#169](https://github.com/trello/RxLifecycle/pull/169): Move to com.trello.rxlifecycle2 - [#170](https://github.com/trello/RxLifecycle/pull/170): Added Maybe support - [#172](https://github.com/trello/RxLifecycle/pull/172): Added Flowable support ## 1.0 (2016-11-03) First and (hopefully) final release of 1.x branch! This release marks the start of maintenance mode for RxJava 1 support. Future work will be devoted to supporting RxJava 2. Important bugs may be squashed but new features will have to be extraordinarily compelling in order to be added. - [#162](https://github.com/trello/RxLifecycle/pull/162): Made all components abstract - [#157](https://github.com/trello/RxLifecycle/pull/157): Added RxPreferenceFragment ## 0.8.0 (2016-09-19) - [#152](https://github.com/trello/RxLifecycle/pull/152): Support RxJava 1.2.0. This change is not backwards compatible with RxJava 1.1.x, so if you want to continue receiving updates for RxLifecycle you will eventually need to upgrade to RxJava 1.2.x. ## 0.7.0 (2016-08-24) There are a couple major breaking changes in this release, so read carefully. - [#143](https://github.com/trello/RxLifecycle/pull/143): Split Android parts of rxlifecycle into rxlifecycle-android Now the `rxlifecycle` dependency is a pure Java core. To use RxLifecycle with Android, you should also include `rxlifecycle-android` as well now. `RxLifecycle` methods that are for Android (`bindActivity()`, `bindFragment()` and `bindView()`) are now in `RxLifecycleAndroid` (found in the `rxlifecycle-android` artifact). Deprecated methods in `RxLifecycle` were removed as well. - [#138](https://github.com/trello/RxLifecycle/pull/138) / [#139](https://github.com/trello/RxLifecycle/pull/139): Replace `ActivityLifecycleProvider` and `FragmentLifecycleProvider` with `LifecycleProvider`. This means that you need to replace `ActivityLifecycleProvider` with `LifecycleProvider` and `FragmentLifecycleProvider` with `LifecycleProvider`. Other changes: - [#140](https://github.com/trello/RxLifecycle/pull/140): Fixed type inference for LifecycleTransformer.forSingle() - [#135](https://github.com/trello/RxLifecycle/pull/135): Add Kotlin extensions for Singles and Completables ## 0.6.1 (2016-05-11) - [#118](https://github.com/trello/RxLifecycle/pull/118): Use `LifecycleTransformer` in the provider interfaces ## 0.6.0 (2016-05-06) - Added `LifecycleTransformer`, which provides `Single` and `Completable` support. - [#111](https://github.com/trello/RxLifecycle/pull/111): Added component support for `AppCompatDialogFragment` - [#107](https://github.com/trello/RxLifecycle/pull/107): Fixed navi component package ## 0.5.0 (2016-02-27) There are a few methods which have been **deprecated** and will be removed in a future release. Each one has a drop-in replacement (and currently calling the deprecated version just routes to the new one): * `bindUntilActivityEvent()` and `bindUntilFragmentEvent()` -> `bindUntilEvent()` * `bindView()` -> `bind()` The other changes mostly involve opening up the API for more customization: * [#78](https://github.com/trello/RxLifecycle/pull/78): Added rxlifecycle-kotlin (adds some extensions) * [#79](https://github.com/trello/RxLifecycle/pull/79): Made bindUntilEvent() public, deprecated more specific calls * [#82](https://github.com/trello/RxLifecycle/pull/82): Opened up bind() methods for public consumption * [#83](https://github.com/trello/RxLifecycle/pull/83), [#85](https://github.com/trello/RxLifecycle/pull/85): Added annotations for better lint checking * [#88](https://github.com/trello/RxLifecycle/pull/88): Use `.equals()` instead of == for event comparison (for custom event support with the newly opened-up `bind()`) * [#89](https://github.com/trello/RxLifecycle/pull/89): Make OutsideLifecycleException public (for anyone who wants to write their own `bind()` implementations) ## 0.4.0 (2015-12-10) * [#62](https://github.com/trello/RxLifecycle/pull/62), [#67](https://github.com/trello/RxLifecycle/pull/67): Added [Navi](https://github.com/trello/navi/)-based implementation of providers. * [#61](https://github.com/trello/RxLifecycle/pull/61): Moved `ActivityLifecycleProvider` and `FragmentLifecycleProvider` into the core library so that multiple implementations can share them easily. The package name changed so you may need to re-import them in your code. * [#60](https://github.com/trello/RxLifecycle/pull/60): Reverted generic parameters back to `Transformer` ## 0.3.1 (2015-11-27) * [#46](https://github.com/trello/RxLifecycle/pull/46): Updated generic parameters of `Transformer` to support Kotlin type inference. ## 0.3.0 * [#12](https://github.com/trello/RxLifecycle/pull/12): Added `RxLifecycle.bindView()`. This allows binding a `Subscription` until a `View` detaches itself from the window. * [#30](https://github.com/trello/RxLifecycle/pull/30): Calling `bindActivity()` or `bindFragment()` outside of the lifecycle causes the sequence to immediately complete (instead of throwing an error). * [#31](https://github.com/trello/RxLifecycle/pull/31): Passing nulls to RxLifecycle now always immediately throws an exception. ## 0.2.0 * [#14](https://github.com/trello/RxLifecycle/pull/14): Use takeUntil internally (instead of a faulty custom operator) While this fixes some intractable problems that could occur with the old system, it also includes a major behavior change: when the bind decides to stop subscribing, it calls `onCompleted` (whereas before it would just unsubscribe). When upgrading, you should check that your usages of `onCompleted` (either in `subscribe()`, `doOnCompleted()`, or `doOnTerminate()`) can handle the sequence ending due to the lifecycle bind. If you still need the old behavior in some spots, you should handle the `Subscription` yourself manually (and call `unsubscribe()` when appropriate). * [#16](https://github.com/trello/RxLifecycle/pull/16): Lowered minSdkVersion to 14 ## 0.1.0 Initial independent release (split from RxAndroid 0.25.0) * Added support for AppCompatActivity via `RxAppCompatActivity` * Components (e.g. `RxActivity`) now support `bindUntilEvent()` and `bindToLifecycle()`, which avoids having to deal with the lifecycle `Observable` directly. ### Differences from RxAndroid 0.25 * Renamed `LifecycleObservable` to `RxLifecycle` * Switched from wrapping `Observables` to using `Transformer` + `compose()` (which allows for chaining) * Split `LifecycleEvent` into two parts - `ActivityEvent` and `FragmentEvent`, in order to prevent easy mixups that could occur before * Split `bindUntilLifecycleEvent()` into `bindUntilFragmentEvent()` and `bindUntilActivityEvent()` * Renamed `bindFragmentLifecycle()` to `bindFragment()` * Renamed `bindActivityLifecycle()` to `bindActivity()` ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # RxLifecycle This library allows one to automatically complete sequences based on a second lifecycle stream. This capability is useful in Android, where incomplete subscriptions can cause memory leaks. ## Usage You must start with an `Observable` representing a lifecycle stream. Then you use `RxLifecycle` to bind a sequence to that lifecycle. You can bind when the lifecycle emits anything: ```java myObservable .compose(RxLifecycle.bind(lifecycle)) .subscribe(); ``` Or you can bind to when a specific lifecyle event occurs: ```java myObservable .compose(RxLifecycle.bindUntilEvent(lifecycle, ActivityEvent.DESTROY)) .subscribe(); ``` Alternatively, you can let RxLifecycle determine the appropriate time to end the sequence: ```java myObservable .compose(RxLifecycleAndroid.bindActivity(lifecycle)) .subscribe(); ``` It assumes you want to end the sequence in the opposing lifecycle event - e.g., if subscribing during `START`, it will terminate on `STOP`. If you subscribe after `PAUSE`, it will terminate at the next destruction event (e.g., `PAUSE` will terminate in `STOP`). ## Providers Where do lifecycles come from? Generally, they are provided by an appropriate `LifecycleProvider`. But where are those implemented? You have a few options for that: 1. Use rxlifecycle-components and subclass the provided `RxActivity`, `RxFragment`, etc. classes. 1. Use [Android's lifecycle](https://developer.android.com/topic/libraries/architecture/lifecycle.html) + rxlifecycle-android-lifecycle to generate providers. 1. Write the implementation yourself. If you use rxlifecycle-components, just extend the appropriate class, then use the built-in `bindToLifecycle()` (or `bindUntilEvent()`) methods: ```java public class MyActivity extends RxActivity { @Override public void onResume() { super.onResume(); myObservable .compose(bindToLifecycle()) .subscribe(); } } ``` If you use rxlifecycle-android-lifecycle, then you just pass your `LifecycleOwner` to `AndroidLifecycle` to generate a provider: ```java public class MyActivity extends LifecycleActivity { private final LifecycleProvider provider = AndroidLifecycle.createLifecycleProvider(this); @Override public void onResume() { super.onResume(); myObservable .compose(provider.bindToLifecycle()) .subscribe(); } } ``` ## Unsubscription RxLifecycle does not actually unsubscribe the sequence. Instead it terminates the sequence. The way in which it does so varies based on the type: - `Observable`, `Flowable` and `Maybe` - emits `onCompleted()` - `Single` and `Completable` - emits `onError(CancellationException)` If a sequence requires the `Subscription.unsubscribe()` behavior, then it is suggested that you manually handle the `Subscription` yourself and call `unsubscribe()` when appropriate. ## Kotlin The rxlifecycle-kotlin module provides built-in extensions to the base RxJava types: ```kotlin myObservable .bindToLifecycle(myView) .subscribe { } myObservable .bindUntilEvent(myRxActivity, STOP) .subscribe { } ``` There is an additional rxlifecycle-android-lifecycle-kotlin module to provider extensions to work with `LifecycleOwner`'s. ```kotlin myObservable .bindUntilEvent(myLifecycleActivity, ON_STOP) .subscribe { } ``` ## Installation ```gradle implementation 'com.trello.rxlifecycle4:rxlifecycle:4.0.2' // If you want to bind to Android-specific lifecycles implementation 'com.trello.rxlifecycle4:rxlifecycle-android:4.0.2' // If you want pre-written Activities and Fragments you can subclass as providers implementation 'com.trello.rxlifecycle4:rxlifecycle-components:4.0.2' // If you want pre-written support preference Fragments you can subclass as providers implementation 'com.trello.rxlifecycle4:rxlifecycle-components-preference:4.0.2' // If you want to use Android Lifecycle for providers implementation 'com.trello.rxlifecycle4:rxlifecycle-android-lifecycle:4.0.2' // If you want to use Kotlin syntax implementation 'com.trello.rxlifecycle4:rxlifecycle-kotlin:4.0.2' // If you want to use Kotlin syntax with Android Lifecycle implementation 'com.trello.rxlifecycle4:rxlifecycle-android-lifecycle-kotlin:4.0.2' ``` ## License Copyright (C) 2016 Trello Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: build.gradle ================================================ buildscript { ext { //version here to share between build script and projects verKotlin = '1.3.72' } repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.6.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$verKotlin" classpath "org.jetbrains.kotlin:kotlin-android-extensions:$verKotlin" classpath 'com.github.ben-manes:gradle-versions-plugin:0.28.0' classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' } } subprojects { group = GROUP version = VERSION_NAME } apply plugin: 'com.github.ben-manes.versions' ext { minSdkVersion = 14 compileSdkVersion = 28 targetSdkVersion = compileSdkVersion sourceCompatibilityVersion = JavaVersion.VERSION_1_7 targetCompatibilityVersion = JavaVersion.VERSION_1_7 // Define all dependencies in the base project, to unify & make it easy to update rxJava = 'io.reactivex.rxjava3:rxjava:3.0.4' rxAndroid = 'io.reactivex.rxjava3:rxandroid:3.0.0' navi = 'com.trello.navi2:navi:2.1.0' lifecycle = 'androidx.lifecycle:lifecycle-runtime:2.2.0' lifecycleProcessor = 'androidx.lifecycle:lifecycle-compiler:2.2.0' lifecycleExtensions = 'androidx.lifecycle:lifecycle-extensions:2.2.0' kotlinStdlib = "org.jetbrains.kotlin:kotlin-stdlib:$verKotlin" appCompat = 'androidx.appcompat:appcompat:1.1.0' preferenceCompat = 'androidx.preference:preference:1.1.1' supportAnnotations = 'androidx.annotation:annotation:1.1.0' jsr305Annotations = 'com.google.code.findbugs:jsr305:3.0.2' junit = 'junit:junit:4.13' robolectric = 'org.robolectric:robolectric:3.8' } ================================================ FILE: gradle/artifacts.gradle ================================================ if (project.plugins.hasPlugin('com.android.library')) { android.libraryVariants.all { variant -> Task javadocTask = task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) { group = 'artifact' description "Generates Javadoc for $variant.name" // Source files from the variant source = variant.javaCompiler.source // Classpath from the variant + android.jar String androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar" classpath = variant.javaCompiler.classpath + files(androidJar) // The Android online reference doesn't include package-list, so we have to use the local one String packageListRef = "${android.sdkDirectory}/docs/reference/" options.linksOffline 'http://d.android.com/reference/', packageListRef // Additional links for any RxJava references options.links 'http://reactivex.io/RxJava/javadoc/' // Exclude generated files exclude '**/BuildConfig.java' exclude '**/R.java' // Output to a unique javadoc folder per variant destinationDir = new File(project.docsDir, "javadoc-$variant.name") } // For official releasese, don't prefix the name so the artifact is published correctly // (Can't seem to modify it for publishing, for whatever reason...) String classifierPrefix = (variant.name == 'release') ? '' : "$variant.name-" Task javadocJarTask = task("generate${variant.name.capitalize()}JavadocJar", type: Jar, dependsOn: javadocTask) { group = 'artifact' description = "Generates Javadoc jar for $variant.name" classifier = "${classifierPrefix}javadoc" from javadocTask.destinationDir } Task sourcesJarTask = task("generate${variant.name.capitalize()}SourcesJar", type: Jar) { group = 'artifact' description = "Generates sources jar for $variant.name" classifier = "${classifierPrefix}sources" from variant.javaCompiler.source } if (variant.name == 'release') { // There's a lot of "magic" around the archives configuration; easier // just to embrace it rather than try to configure around it artifacts { archives javadocJarTask, sourcesJarTask } } else { // Create a configuration we can publish from for each variant String configurationName = "archives${variant.name.capitalize()}" configurations.create(configurationName) artifacts.add configurationName, javadocJarTask artifacts.add configurationName, sourcesJarTask } } } ================================================ FILE: gradle/gradle-mvn-push.gradle ================================================ /* * Copyright 2013 Chris Banes * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ apply plugin: 'maven' apply plugin: 'signing' def isReleaseBuild() { return VERSION_NAME.contains("SNAPSHOT") == false } def getRepositoryUsername() { return hasProperty('SONATYPE_NEXUS_USERNAME') ? SONATYPE_NEXUS_USERNAME : "" } def getRepositoryPassword() { return hasProperty('SONATYPE_NEXUS_PASSWORD') ? SONATYPE_NEXUS_PASSWORD : "" } afterEvaluate { project -> uploadArchives { repositories { mavenDeployer { beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } pom.groupId = GROUP pom.artifactId = POM_ARTIFACT_ID pom.version = VERSION_NAME repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) } snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) } pom.project { name POM_NAME packaging POM_PACKAGING description POM_DESCRIPTION url POM_URL scm { url POM_SCM_URL connection POM_SCM_CONNECTION developerConnection POM_SCM_DEV_CONNECTION } licenses { license { name POM_LICENCE_NAME url POM_LICENCE_URL distribution POM_LICENCE_DIST } } developers { developer { id POM_DEVELOPER_ID name POM_DEVELOPER_NAME } } } } } } signing { required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } sign configurations.archives } } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.4.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ GROUP=com.trello.rxlifecycle4 VERSION_NAME=4.0.2-SNAPSHOT POM_URL=https://github.com/trello/RxLifecycle POM_SCM_URL=https://github.com/trello/RxLifecycle POM_SCM_CONNECTION=scm:git:https://github.com/trello/RxLifecycle.git POM_SCM_DEV_CONNECTION=scm:git:git@github.com:trello/RxLifecycle.git POM_LICENCE_NAME=The Apache Software License, Version 2.0 POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt POM_LICENCE_DIST=repo POM_DEVELOPER_ID=dlew POM_DEVELOPER_NAME=Dan Lew android.useAndroidX=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh # # Copyright 2015 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=`expr $i + 1` done case $i in 0) set -- ;; 1) set -- "$args0" ;; 2) set -- "$args0" "$args1" ;; 3) set -- "$args0" "$args1" "$args2" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: rxlifecycle/build.gradle ================================================ apply plugin: 'java' sourceCompatibility = rootProject.ext.sourceCompatibilityVersion targetCompatibility = rootProject.ext.targetCompatibilityVersion repositories { mavenCentral() } dependencies { compile rootProject.ext.rxJava compileOnly rootProject.ext.jsr305Annotations testImplementation rootProject.ext.junit } // Add sources/javadoc artifacts task sourcesJar(type: Jar, dependsOn:classes) { classifier = 'sources' from sourceSets.main.allSource } task javadocJar(type: Jar, dependsOn:javadoc) { classifier = 'javadoc' from javadoc.destinationDir } artifacts { archives sourcesJar archives javadocJar } apply from: "$rootDir/gradle/gradle-mvn-push.gradle" ================================================ FILE: rxlifecycle/gradle.properties ================================================ POM_NAME=RxLifecycle POM_DESCRIPTION=RxLifecycle POM_ARTIFACT_ID=rxlifecycle POM_PACKAGING=aar ================================================ FILE: rxlifecycle/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxlifecycle/src/main/java/com/trello/rxlifecycle4/Functions.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import java.util.concurrent.CancellationException; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.exceptions.Exceptions; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.functions.Predicate; final class Functions { static final Function RESUME_FUNCTION = new Function() { @Override public Boolean apply(Throwable throwable) throws Exception { if (throwable instanceof OutsideLifecycleException) { return true; } //noinspection ThrowableResultOfMethodCallIgnored Exceptions.propagate(throwable); return false; } }; static final Predicate SHOULD_COMPLETE = new Predicate() { @Override public boolean test(Boolean shouldComplete) throws Exception { return shouldComplete; } }; static final Function CANCEL_COMPLETABLE = new Function() { @Override public Completable apply(Object ignore) throws Exception { return Completable.error(new CancellationException()); } }; private Functions() { throw new AssertionError("No instances!"); } } ================================================ FILE: rxlifecycle/src/main/java/com/trello/rxlifecycle4/LifecycleProvider.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import io.reactivex.rxjava3.core.Observable; /** * Common base interface for activity and fragment lifecycle providers. * * Useful if you are writing utilities on top of rxlifecycle-components * or implementing your own component not supported by this library. */ public interface LifecycleProvider { /** * @return a sequence of lifecycle events */ @Nonnull @CheckReturnValue Observable lifecycle(); /** * Binds a source until a specific event occurs. * * @param event the event that triggers unsubscription * @return a reusable {@link LifecycleTransformer} which unsubscribes when the event triggers. */ @Nonnull @CheckReturnValue LifecycleTransformer bindUntilEvent(@Nonnull E event); /** * Binds a source until the next reasonable event occurs. * * @return a reusable {@link LifecycleTransformer} which unsubscribes at the correct time. */ @Nonnull @CheckReturnValue LifecycleTransformer bindToLifecycle(); } ================================================ FILE: rxlifecycle/src/main/java/com/trello/rxlifecycle4/LifecycleTransformer.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.reactivestreams.Publisher; import javax.annotation.ParametersAreNonnullByDefault; import io.reactivex.rxjava3.core.BackpressureStrategy; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.CompletableSource; import io.reactivex.rxjava3.core.CompletableTransformer; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.FlowableTransformer; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.core.MaybeSource; import io.reactivex.rxjava3.core.MaybeTransformer; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.ObservableSource; import io.reactivex.rxjava3.core.ObservableTransformer; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.core.SingleSource; import io.reactivex.rxjava3.core.SingleTransformer; import static com.trello.rxlifecycle4.internal.Preconditions.checkNotNull; /** * Transformer that continues a subscription until a second Observable emits an event. */ @ParametersAreNonnullByDefault public final class LifecycleTransformer implements ObservableTransformer, FlowableTransformer, SingleTransformer, MaybeTransformer, CompletableTransformer { final Observable observable; LifecycleTransformer(Observable observable) { checkNotNull(observable, "observable == null"); this.observable = observable; } @Override public ObservableSource apply(Observable upstream) { return upstream.takeUntil(observable); } @Override public Publisher apply(Flowable upstream) { return upstream.takeUntil(observable.toFlowable(BackpressureStrategy.LATEST)); } @Override public SingleSource apply(Single upstream) { return upstream.takeUntil(observable.firstOrError()); } @Override public MaybeSource apply(Maybe upstream) { return upstream.takeUntil(observable.firstElement()); } @Override public CompletableSource apply(Completable upstream) { return Completable.ambArray(upstream, observable.flatMapCompletable(Functions.CANCEL_COMPLETABLE)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LifecycleTransformer that = (LifecycleTransformer) o; return observable.equals(that.observable); } @Override public int hashCode() { return observable.hashCode(); } @Override public String toString() { return "LifecycleTransformer{" + "observable=" + observable + '}'; } } ================================================ FILE: rxlifecycle/src/main/java/com/trello/rxlifecycle4/OutsideLifecycleException.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import javax.annotation.Nullable; /** * This is an exception that can be thrown to indicate that the caller has attempted to bind to a lifecycle outside * of its allowable window. */ public class OutsideLifecycleException extends IllegalStateException { public OutsideLifecycleException(@Nullable String detailMessage) { super(detailMessage); } } ================================================ FILE: rxlifecycle/src/main/java/com/trello/rxlifecycle4/RxLifecycle.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.functions.BiFunction; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.functions.Predicate; import static com.trello.rxlifecycle4.internal.Preconditions.checkNotNull; public class RxLifecycle { private RxLifecycle() { throw new AssertionError("No instances"); } /** * Binds the given source to a lifecycle. *

* When the lifecycle event occurs, the source will cease to emit any notifications. * * @param lifecycle the lifecycle sequence * @param event the event which should conclude notifications from the source * @return a reusable {@link LifecycleTransformer} that unsubscribes the source at the specified event */ @Nonnull @CheckReturnValue public static LifecycleTransformer bindUntilEvent(@Nonnull final Observable lifecycle, @Nonnull final R event) { checkNotNull(lifecycle, "lifecycle == null"); checkNotNull(event, "event == null"); return bind(takeUntilEvent(lifecycle, event)); } private static Observable takeUntilEvent(final Observable lifecycle, final R event) { return lifecycle.filter(new Predicate() { @Override public boolean test(R lifecycleEvent) throws Exception { return lifecycleEvent.equals(event); } }); } /** * Binds the given source to a lifecycle. *

* This helper automatically determines (based on the lifecycle sequence itself) when the source * should stop emitting items. Note that for this method, it assumes any event * emitted by the given lifecycle indicates that the lifecycle is over. * * @param lifecycle the lifecycle sequence * @return a reusable {@link LifecycleTransformer} that unsubscribes the source whenever the lifecycle emits */ @Nonnull @CheckReturnValue public static LifecycleTransformer bind(@Nonnull final Observable lifecycle) { return new LifecycleTransformer<>(lifecycle); } /** * Binds the given source to a lifecycle. *

* This method determines (based on the lifecycle sequence itself) when the source * should stop emitting items. It uses the provided correspondingEvents function to determine * when to unsubscribe. *

* Note that this is an advanced usage of the library and should generally be used only if you * really know what you're doing with a given lifecycle. * * @param lifecycle the lifecycle sequence * @param correspondingEvents a function which tells the source when to unsubscribe * @return a reusable {@link LifecycleTransformer} that unsubscribes the source during the Fragment lifecycle */ @Nonnull @CheckReturnValue public static LifecycleTransformer bind(@Nonnull Observable lifecycle, @Nonnull final Function correspondingEvents) { checkNotNull(lifecycle, "lifecycle == null"); checkNotNull(correspondingEvents, "correspondingEvents == null"); return bind(takeUntilCorrespondingEvent(lifecycle.share(), correspondingEvents)); } private static Observable takeUntilCorrespondingEvent(final Observable lifecycle, final Function correspondingEvents) { return Observable.combineLatest( lifecycle.take(1).map(correspondingEvents), lifecycle.skip(1), new BiFunction() { @Override public Boolean apply(R bindUntilEvent, R lifecycleEvent) throws Exception { return lifecycleEvent.equals(bindUntilEvent); } }) .onErrorReturn(Functions.RESUME_FUNCTION) .filter(Functions.SHOULD_COMPLETE); } } ================================================ FILE: rxlifecycle/src/main/java/com/trello/rxlifecycle4/internal/Preconditions.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.internal; public final class Preconditions { public static T checkNotNull(T value, String message) { if (value == null) { throw new NullPointerException(message); } return value; } private Preconditions() { throw new AssertionError("No instances."); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/OutsideLifecycleExceptionTest.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Test; import io.reactivex.rxjava3.exceptions.CompositeException; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.functions.Predicate; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class OutsideLifecycleExceptionTest { @Test public void eventOutOfLifecycle() { PublishSubject stream = PublishSubject.create(); PublishSubject lifecycle = PublishSubject.create(); TestObserver testObserver = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); // Event is out of lifecycle, but this just results in completing the stream lifecycle.onNext("destroy"); stream.onNext("1"); testObserver.assertNoValues(); testObserver.assertComplete(); } @Test public void eventThrowsBadException() { PublishSubject stream = PublishSubject.create(); PublishSubject lifecycle = PublishSubject.create(); TestObserver testObserver = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); // We get an error from the function for this lifecycle event lifecycle.onNext("ick"); stream.onNext("1"); testObserver.assertNoValues(); // We only want to check for our IllegalArgumentException, but may have // to wade through a CompositeException to get at it. testObserver.assertError(new Predicate() { @Override public boolean test(Throwable throwable) throws Exception { if (throwable instanceof CompositeException) { CompositeException ce = (CompositeException) throwable; for (Throwable t : ce.getExceptions()) { if (t instanceof IllegalArgumentException) { return true; } } } return false; } }); } private static final Function CORRESPONDING_EVENTS = new Function() { @Override public String apply(String s) throws Exception { if (s.equals("destroy")) { throw new OutsideLifecycleException(""); } throw new IllegalArgumentException("Cannot handle: " + s); } }; } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/RxLifecycleTest.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.BehaviorSubject; import io.reactivex.rxjava3.subjects.PublishSubject; public class RxLifecycleTest { private Observable observable; @Before public void setup() { // Simulate an actual lifecycle (hot Observable that does not end) observable = PublishSubject.create().hide(); } @Test public void testBindLifecycle() { BehaviorSubject lifecycle = BehaviorSubject.create(); TestObserver testObserver = observable.compose(RxLifecycle.bind(lifecycle)).test(); testObserver.assertNotComplete(); lifecycle.onNext(new Object()); testObserver.assertComplete(); } @Test public void testBindLifecycleOtherObject() { // Ensures it works with other types as well, and not just "Object" BehaviorSubject lifecycle = BehaviorSubject.create(); TestObserver testObserver = observable.compose(RxLifecycle.bind(lifecycle)).test(); testObserver.assertNotComplete(); lifecycle.onNext(""); testObserver.assertComplete(); } // Null checks @Test(expected=NullPointerException.class) public void testBindThrowsOnNullLifecycle() { //noinspection ResourceType RxLifecycle.bind((Observable) null); } @Test(expected = NullPointerException.class) public void testBindUntilThrowsOnNullLifecycle() { //noinspection ResourceType RxLifecycle.bindUntilEvent(null, new Object()); } @Test(expected = NullPointerException.class) public void testBindUntilThrowsOnNullEvent() { BehaviorSubject lifecycle = BehaviorSubject.create(); //noinspection ResourceType RxLifecycle.bindUntilEvent(lifecycle, null); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilCorrespondingEventTransformerCompletableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import java.util.concurrent.CancellationException; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilCorrespondingEventTransformerCompletableTest { PublishSubject subject; Completable completable; PublishSubject lifecycle; @Before public void setup() { subject = PublishSubject.create(); completable = Completable.fromObservable(subject); lifecycle = PublishSubject.create(); } @Test public void noEvents() { TestObserver testObserver = completable .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); subject.onComplete(); testObserver.assertComplete(); } @Test public void oneStartEvent() { TestObserver testObserver = completable .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); subject.onComplete(); testObserver.assertComplete(); } @Test public void twoOpenEvents() { TestObserver testObserver = completable .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); lifecycle.onNext("start"); subject.onComplete(); testObserver.assertComplete(); } @Test public void openAndCloseEvent() { TestObserver testObserver = completable .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); lifecycle.onNext("destroy"); subject.onComplete(); testObserver.assertError(CancellationException.class); } private static final Function CORRESPONDING_EVENTS = new Function() { @Override public String apply(String s) throws Exception { if (s.equals("create")) { return "destroy"; } throw new IllegalArgumentException("Cannot handle: " + s); } }; } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilCorrespondingEventTransformerFlowableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.processors.PublishProcessor; import io.reactivex.rxjava3.subjects.PublishSubject; import io.reactivex.rxjava3.subscribers.TestSubscriber; public class UntilCorrespondingEventTransformerFlowableTest { PublishProcessor stream; PublishSubject lifecycle; @Before public void setup() { stream = PublishProcessor.create(); lifecycle = PublishSubject.create(); } @Test public void noEvents() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); stream.onNext("1"); stream.onNext("2"); testSubscriber.assertValues("1", "2"); testSubscriber.assertNotComplete(); } @Test public void oneStartEvent() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); stream.onNext("1"); stream.onNext("2"); testSubscriber.assertValues("1", "2"); testSubscriber.assertNotComplete(); } @Test public void twoOpenEvents() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); stream.onNext("1"); lifecycle.onNext("start"); stream.onNext("2"); testSubscriber.assertValues("1", "2"); testSubscriber.assertNotComplete(); } @Test public void openAndCloseEvent() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); stream.onNext("1"); lifecycle.onNext("destroy"); stream.onNext("2"); testSubscriber.assertValues("1"); testSubscriber.assertComplete(); } private static final Function CORRESPONDING_EVENTS = new Function() { @Override public String apply(String s) throws Exception { if (s.equals("create")) { return "destroy"; } throw new IllegalArgumentException("Cannot handle: " + s); } }; } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilCorrespondingEventTransformerMaybeTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilCorrespondingEventTransformerMaybeTest { PublishSubject subject; Maybe maybe; PublishSubject lifecycle; @Before public void setup() { subject = PublishSubject.create(); maybe = subject.firstElement(); lifecycle = PublishSubject.create(); } @Test public void noEvents() { TestObserver testObserver = maybe .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); subject.onNext("1"); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void oneStartEvent() { TestObserver testObserver = maybe .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); subject.onNext("1"); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void twoOpenEvents() { TestObserver testObserver = maybe .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); lifecycle.onNext("start"); subject.onNext("1"); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void openAndCloseEvent() { TestObserver testObserver = maybe .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); lifecycle.onNext("destroy"); subject.onNext("1"); testObserver.assertNoValues(); testObserver.assertComplete(); } private static final Function CORRESPONDING_EVENTS = new Function() { @Override public String apply(String s) throws Exception { if (s.equals("create")) { return "destroy"; } throw new IllegalArgumentException("Cannot handle: " + s); } }; } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilCorrespondingEventTransformerObservableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilCorrespondingEventTransformerObservableTest { PublishSubject stream; PublishSubject lifecycle; @Before public void setup() { stream = PublishSubject.create(); lifecycle = PublishSubject.create(); } @Test public void noEvents() { TestObserver testObserver = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); stream.onNext("1"); stream.onNext("2"); testObserver.assertValues("1", "2"); testObserver.assertNotComplete(); } @Test public void oneStartEvent() { TestObserver testObserver = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); stream.onNext("1"); stream.onNext("2"); testObserver.assertValues("1", "2"); testObserver.assertNotComplete(); } @Test public void twoOpenEvents() { TestObserver testObserver = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); stream.onNext("1"); lifecycle.onNext("start"); stream.onNext("2"); testObserver.assertValues("1", "2"); testObserver.assertNotComplete(); } @Test public void openAndCloseEvent() { TestObserver testObserver = stream .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); stream.onNext("1"); lifecycle.onNext("destroy"); stream.onNext("2"); testObserver.assertValues("1"); testObserver.assertComplete(); } private static final Function CORRESPONDING_EVENTS = new Function() { @Override public String apply(String s) throws Exception { if (s.equals("create")) { return "destroy"; } throw new IllegalArgumentException("Cannot handle: " + s); } }; } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilCorrespondingEventTransformerSingleTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import java.util.concurrent.CancellationException; import java.util.concurrent.TimeUnit; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.functions.Function; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.schedulers.TestScheduler; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilCorrespondingEventTransformerSingleTest { PublishSubject lifecycle; TestScheduler testScheduler; // Since Single is not backpressure aware, use this to simulate it taking time @Before public void setup() { lifecycle = PublishSubject.create(); testScheduler = new TestScheduler(); } @Test public void noEvents() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); testObserver.assertNoValues(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void oneStartEvent() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); testObserver.assertNoValues(); lifecycle.onNext("create"); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void twoOpenEvents() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); testObserver.assertNoValues(); lifecycle.onNext("create"); lifecycle.onNext("start"); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void openAndCloseEvent() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bind(lifecycle, CORRESPONDING_EVENTS)) .test(); lifecycle.onNext("create"); testObserver.assertNoErrors(); lifecycle.onNext("destroy"); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertNoValues(); testObserver.assertError(CancellationException.class); } private static final Function CORRESPONDING_EVENTS = new Function() { @Override public String apply(String s) throws Exception { if (s.equals("create")) { return "destroy"; } throw new IllegalArgumentException("Cannot handle: " + s); } }; } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilEventTransformerCompletableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import java.util.concurrent.CancellationException; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilEventTransformerCompletableTest { PublishSubject subject; Completable completable; PublishSubject lifecycle; @Before public void setup() { subject = PublishSubject.create(); completable = Completable.fromObservable(subject); lifecycle = PublishSubject.create(); } @Test public void noEvents() { TestObserver testObserver = completable .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); subject.onComplete(); testObserver.assertComplete(); } @Test public void oneWrongEvent() { TestObserver testObserver = completable .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); lifecycle.onNext("keep going"); subject.onComplete(); testObserver.assertComplete(); } @Test public void twoEvents() { TestObserver testObserver = completable .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); lifecycle.onNext("keep going"); lifecycle.onNext("stop"); subject.onComplete(); testObserver.assertError(CancellationException.class); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilEventTransformerFlowableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.processors.PublishProcessor; import io.reactivex.rxjava3.subjects.PublishSubject; import io.reactivex.rxjava3.subscribers.TestSubscriber; public class UntilEventTransformerFlowableTest { PublishProcessor stream; PublishSubject lifecycle; @Before public void setup() { stream = PublishProcessor.create(); lifecycle = PublishSubject.create(); } @Test public void noEvents() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); stream.onNext("1"); stream.onNext("2"); testSubscriber.assertValues("1", "2"); testSubscriber.assertNotComplete(); } @Test public void oneWrongEvent() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); stream.onNext("1"); lifecycle.onNext("keep going"); stream.onNext("2"); testSubscriber.assertValues("1", "2"); testSubscriber.assertNotComplete(); } @Test public void twoEvents() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); stream.onNext("1"); lifecycle.onNext("keep going"); stream.onNext("2"); lifecycle.onNext("stop"); stream.onNext("3"); testSubscriber.assertValues("1", "2"); testSubscriber.assertComplete(); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilEventTransformerMaybeTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilEventTransformerMaybeTest { PublishSubject subject; Maybe maybe; PublishSubject lifecycle; @Before public void setup() { subject = PublishSubject.create(); maybe = subject.firstElement(); lifecycle = PublishSubject.create(); } @Test public void noEvents() { TestObserver testObserver = maybe .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); subject.onNext("1"); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void oneWrongEvent() { TestObserver testObserver = maybe .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); lifecycle.onNext("keep going"); subject.onNext("1"); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void twoEvents() { TestObserver testObserver = maybe .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); lifecycle.onNext("keep going"); lifecycle.onNext("stop"); subject.onNext("1"); testObserver.assertNoValues(); testObserver.assertComplete(); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilEventTransformerObservableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilEventTransformerObservableTest { PublishSubject stream; PublishSubject lifecycle; @Before public void setup() { stream = PublishSubject.create(); lifecycle = PublishSubject.create(); } @Test public void noEvents() { TestObserver testObserver = stream .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); stream.onNext("1"); stream.onNext("2"); testObserver.assertValues("1", "2"); testObserver.assertNotComplete(); } @Test public void oneWrongEvent() { TestObserver testObserver = stream .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); stream.onNext("1"); lifecycle.onNext("keep going"); stream.onNext("2"); testObserver.assertValues("1", "2"); testObserver.assertNotComplete(); } @Test public void twoEvents() { TestObserver testObserver = stream .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); stream.onNext("1"); lifecycle.onNext("keep going"); stream.onNext("2"); lifecycle.onNext("stop"); stream.onNext("3"); testObserver.assertValues("1", "2"); testObserver.assertComplete(); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilEventTransformerSingleTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import java.util.concurrent.CancellationException; import java.util.concurrent.TimeUnit; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.schedulers.TestScheduler; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilEventTransformerSingleTest { PublishSubject lifecycle; TestScheduler testScheduler; // Since Single is not backpressure aware, use this to simulate it taking time @Before public void setup() { lifecycle = PublishSubject.create(); testScheduler = new TestScheduler(); } @Test public void noEvents() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); testObserver.assertNoValues(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void oneWrongEvent() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); testObserver.assertNoValues(); lifecycle.onNext("keep going"); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void twoEvents() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bindUntilEvent(lifecycle, "stop")) .test(); lifecycle.onNext("keep going"); testObserver.assertNoErrors(); lifecycle.onNext("stop"); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertNoValues(); testObserver.assertError(CancellationException.class); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilLifecycleTransformerCompletableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import java.util.concurrent.CancellationException; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilLifecycleTransformerCompletableTest { PublishSubject subject; Completable completable; PublishSubject lifecycle; @Before public void setup() { subject = PublishSubject.create(); completable = Completable.fromObservable(subject); lifecycle = PublishSubject.create(); } @Test public void noEvent() { TestObserver testObserver = completable .compose(RxLifecycle.bind(lifecycle)) .test(); subject.onComplete(); testObserver.assertComplete(); } @Test public void oneEvent() { TestObserver testObserver = completable .compose(RxLifecycle.bind(lifecycle)) .test(); lifecycle.onNext("stop"); subject.onComplete(); testObserver.assertError(CancellationException.class); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilLifecycleTransformerFlowableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.processors.PublishProcessor; import io.reactivex.rxjava3.subjects.PublishSubject; import io.reactivex.rxjava3.subscribers.TestSubscriber; public class UntilLifecycleTransformerFlowableTest { PublishProcessor stream; PublishSubject lifecycle; @Before public void setup() { stream = PublishProcessor.create(); lifecycle = PublishSubject.create(); } @Test public void noEvent() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bind(lifecycle)) .test(); stream.onNext("1"); stream.onNext("2"); testSubscriber.assertValues("1", "2"); testSubscriber.assertNotComplete(); } @Test public void oneEvent() { TestSubscriber testSubscriber = stream .compose(RxLifecycle.bind(lifecycle)) .test(); stream.onNext("1"); lifecycle.onNext("stop"); stream.onNext("2"); testSubscriber.assertValues("1"); testSubscriber.assertComplete(); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilLifecycleTransformerMaybeTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilLifecycleTransformerMaybeTest { PublishSubject stream; Maybe maybe; PublishSubject lifecycle; @Before public void setup() { stream = PublishSubject.create(); maybe = stream.firstElement(); lifecycle = PublishSubject.create(); } @Test public void noEvent() { TestObserver testObserver = maybe .compose(RxLifecycle.bind(lifecycle)) .test(); stream.onNext("1"); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void oneEvent() { TestObserver testObserver = maybe .compose(RxLifecycle.bind(lifecycle)) .test(); lifecycle.onNext("stop"); stream.onNext("1"); testObserver.assertNoValues(); testObserver.assertComplete(); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilLifecycleTransformerObservableTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilLifecycleTransformerObservableTest { PublishSubject stream; PublishSubject lifecycle; @Before public void setup() { stream = PublishSubject.create(); lifecycle = PublishSubject.create(); } @Test public void noEvent() { TestObserver testObserver = stream .compose(RxLifecycle.bind(lifecycle)) .test(); stream.onNext("1"); stream.onNext("2"); testObserver.assertValues("1", "2"); testObserver.assertNotComplete(); } @Test public void oneEvent() { TestObserver testObserver = stream .compose(RxLifecycle.bind(lifecycle)) .test(); stream.onNext("1"); lifecycle.onNext("stop"); stream.onNext("2"); testObserver.assertValues("1"); testObserver.assertComplete(); } } ================================================ FILE: rxlifecycle/src/test/java/com/trello/rxlifecycle4/UntilLifecycleTransformerSingleTest.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import org.junit.Before; import org.junit.Test; import java.util.concurrent.CancellationException; import java.util.concurrent.TimeUnit; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.schedulers.TestScheduler; import io.reactivex.rxjava3.subjects.PublishSubject; public class UntilLifecycleTransformerSingleTest { PublishSubject lifecycle; TestScheduler testScheduler; // Since Single is not backpressure aware, use this to simulate it taking time @Before public void setup() { lifecycle = PublishSubject.create(); testScheduler = new TestScheduler(); } @Test public void noEvent() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bind(lifecycle)) .test(); testObserver.assertNoValues(); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertValue("1"); testObserver.assertComplete(); } @Test public void oneEvent() { TestObserver testObserver = Single.just("1") .delay(1, TimeUnit.MILLISECONDS, testScheduler) .compose(RxLifecycle.bind(lifecycle)) .test(); testObserver.assertNoValues(); testObserver.assertNoErrors(); lifecycle.onNext("stop"); testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); testObserver.assertNoValues(); testObserver.assertError(CancellationException.class); } } ================================================ FILE: rxlifecycle-android/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion } } repositories { mavenCentral() google() jcenter() } dependencies { api project(':rxlifecycle') implementation rootProject.ext.rxAndroid implementation rootProject.ext.supportAnnotations testImplementation rootProject.ext.junit testImplementation rootProject.ext.robolectric } apply from: "$rootDir/gradle/artifacts.gradle" apply from: "$rootDir/gradle/gradle-mvn-push.gradle" ================================================ FILE: rxlifecycle-android/gradle.properties ================================================ POM_NAME=RxLifecycle-Android POM_DESCRIPTION=RxLifecycle-Android POM_ARTIFACT_ID=rxlifecycle-android POM_PACKAGING=aar ================================================ FILE: rxlifecycle-android/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxlifecycle-android/src/main/java/com/trello/rxlifecycle4/android/ActivityEvent.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.android; /** * Lifecycle events that can be emitted by Activities. */ public enum ActivityEvent { CREATE, START, RESUME, PAUSE, STOP, DESTROY } ================================================ FILE: rxlifecycle-android/src/main/java/com/trello/rxlifecycle4/android/FragmentEvent.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.android; /** * Lifecycle events that can be emitted by Fragments. */ public enum FragmentEvent { ATTACH, CREATE, CREATE_VIEW, START, RESUME, PAUSE, STOP, DESTROY_VIEW, DESTROY, DETACH } ================================================ FILE: rxlifecycle-android/src/main/java/com/trello/rxlifecycle4/android/RxLifecycleAndroid.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.android; import android.view.View; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.OutsideLifecycleException; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.functions.Function; import static com.trello.rxlifecycle4.RxLifecycle.bind; import static com.trello.rxlifecycle4.internal.Preconditions.checkNotNull; public class RxLifecycleAndroid { private RxLifecycleAndroid() { throw new AssertionError("No instances"); } /** * Binds the given source to an Activity lifecycle. *

* This helper automatically determines (based on the lifecycle sequence itself) when the source * should stop emitting items. In the case that the lifecycle sequence is in the * creation phase (CREATE, START, etc) it will choose the equivalent destructive phase (DESTROY, * STOP, etc). If used in the destructive phase, the notifications will cease at the next event; * for example, if used in PAUSE, it will unsubscribe in STOP. *

* Due to the differences between the Activity and Fragment lifecycles, this method should only * be used for an Activity lifecycle. * * @param lifecycle the lifecycle sequence of an Activity * @return a reusable {@link LifecycleTransformer} that unsubscribes the source during the Activity lifecycle */ @NonNull @CheckResult public static LifecycleTransformer bindActivity(@NonNull final Observable lifecycle) { return bind(lifecycle, ACTIVITY_LIFECYCLE); } /** * Binds the given source to a Fragment lifecycle. *

* This helper automatically determines (based on the lifecycle sequence itself) when the source * should stop emitting items. In the case that the lifecycle sequence is in the * creation phase (CREATE, START, etc) it will choose the equivalent destructive phase (DESTROY, * STOP, etc). If used in the destructive phase, the notifications will cease at the next event; * for example, if used in PAUSE, it will unsubscribe in STOP. *

* Due to the differences between the Activity and Fragment lifecycles, this method should only * be used for a Fragment lifecycle. * * @param lifecycle the lifecycle sequence of a Fragment * @return a reusable {@link LifecycleTransformer} that unsubscribes the source during the Fragment lifecycle */ @NonNull @CheckResult public static LifecycleTransformer bindFragment(@NonNull final Observable lifecycle) { return bind(lifecycle, FRAGMENT_LIFECYCLE); } /** * Binds the given source to a View lifecycle. *

* Specifically, when the View detaches from the window, the sequence will be completed. *

* Warning: you should make sure to use the returned Transformer on the main thread, * since we're binding to a View (which only allows binding on the main thread). * * @param view the view to bind the source sequence to * @return a reusable {@link LifecycleTransformer} that unsubscribes the source during the View lifecycle */ @NonNull @CheckResult public static LifecycleTransformer bindView(@NonNull final View view) { checkNotNull(view, "view == null"); return bind(Observable.create(new ViewDetachesOnSubscribe(view))); } // Figures out which corresponding next lifecycle event in which to unsubscribe, for Activities private static final Function ACTIVITY_LIFECYCLE = new Function() { @Override public ActivityEvent apply(ActivityEvent lastEvent) throws Exception { switch (lastEvent) { case CREATE: return ActivityEvent.DESTROY; case START: return ActivityEvent.STOP; case RESUME: return ActivityEvent.PAUSE; case PAUSE: return ActivityEvent.STOP; case STOP: return ActivityEvent.DESTROY; case DESTROY: throw new OutsideLifecycleException("Cannot bind to Activity lifecycle when outside of it."); default: throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented"); } } }; // Figures out which corresponding next lifecycle event in which to unsubscribe, for Fragments private static final Function FRAGMENT_LIFECYCLE = new Function() { @Override public FragmentEvent apply(FragmentEvent lastEvent) throws Exception { switch (lastEvent) { case ATTACH: return FragmentEvent.DETACH; case CREATE: return FragmentEvent.DESTROY; case CREATE_VIEW: return FragmentEvent.DESTROY_VIEW; case START: return FragmentEvent.STOP; case RESUME: return FragmentEvent.PAUSE; case PAUSE: return FragmentEvent.STOP; case STOP: return FragmentEvent.DESTROY_VIEW; case DESTROY_VIEW: return FragmentEvent.DESTROY; case DESTROY: return FragmentEvent.DETACH; case DETACH: throw new OutsideLifecycleException("Cannot bind to Fragment lifecycle when outside of it."); default: throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented"); } } }; } ================================================ FILE: rxlifecycle-android/src/main/java/com/trello/rxlifecycle4/android/ViewDetachesOnSubscribe.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.android; import android.view.View; import io.reactivex.rxjava3.core.ObservableEmitter; import io.reactivex.rxjava3.core.ObservableOnSubscribe; import io.reactivex.rxjava3.android.MainThreadDisposable; import static io.reactivex.rxjava3.android.MainThreadDisposable.verifyMainThread; final class ViewDetachesOnSubscribe implements ObservableOnSubscribe { static final Object SIGNAL = new Object(); final View view; public ViewDetachesOnSubscribe(View view) { this.view = view; } @Override public void subscribe(ObservableEmitter emitter) throws Exception { verifyMainThread(); EmitterListener listener = new EmitterListener(emitter); emitter.setDisposable(listener); view.addOnAttachStateChangeListener(listener); } class EmitterListener extends MainThreadDisposable implements View.OnAttachStateChangeListener { final ObservableEmitter emitter; public EmitterListener(ObservableEmitter emitter) { this.emitter = emitter; } @Override public void onViewAttachedToWindow(View view) { // Do nothing } @Override public void onViewDetachedFromWindow(View view) { emitter.onNext(SIGNAL); } @Override protected void onDispose() { view.removeOnAttachStateChangeListener(this); } } } ================================================ FILE: rxlifecycle-android/src/test/java/com/trello/rxlifecycle4/RxLifecycleTest.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import android.app.Activity; import android.view.View; import com.trello.rxlifecycle4.android.ActivityEvent; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import java.util.concurrent.CopyOnWriteArrayList; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.BehaviorSubject; import io.reactivex.rxjava3.subjects.PublishSubject; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class RxLifecycleTest { private Observable observable; @Before public void setup() { // Simulate an actual lifecycle (hot Observable that does not end) observable = PublishSubject.create().hide(); } @Test public void testBindUntilFragmentEvent() { BehaviorSubject lifecycle = BehaviorSubject.create(); TestObserver testObserver = observable.compose(RxLifecycle.bindUntilEvent(lifecycle, FragmentEvent.STOP)).test(); lifecycle.onNext(FragmentEvent.ATTACH); testObserver.assertNotComplete(); lifecycle.onNext(FragmentEvent.CREATE); testObserver.assertNotComplete(); lifecycle.onNext(FragmentEvent.CREATE_VIEW); testObserver.assertNotComplete(); lifecycle.onNext(FragmentEvent.START); testObserver.assertNotComplete(); lifecycle.onNext(FragmentEvent.RESUME); testObserver.assertNotComplete(); lifecycle.onNext(FragmentEvent.PAUSE); testObserver.assertNotComplete(); testObserver.assertNotComplete(); lifecycle.onNext(FragmentEvent.STOP); testObserver.assertComplete(); } @Test public void testBindUntilActivityEvent() { BehaviorSubject lifecycle = BehaviorSubject.create(); TestObserver testObserver = observable.compose(RxLifecycle.bindUntilEvent(lifecycle, ActivityEvent.STOP)).test(); lifecycle.onNext(ActivityEvent.CREATE); testObserver.assertNotComplete(); lifecycle.onNext(ActivityEvent.START); testObserver.assertNotComplete(); lifecycle.onNext(ActivityEvent.RESUME); testObserver.assertNotComplete(); lifecycle.onNext(ActivityEvent.PAUSE); testObserver.assertNotComplete(); lifecycle.onNext(ActivityEvent.STOP); testObserver.assertComplete(); } @Test public void testBindActivityLifecycle() { BehaviorSubject lifecycle = BehaviorSubject.create(); lifecycle.onNext(ActivityEvent.CREATE); TestObserver createObserver = observable.compose(RxLifecycleAndroid.bindActivity(lifecycle)).test(); lifecycle.onNext(ActivityEvent.START); createObserver.assertNotComplete(); TestObserver startObserver = observable.compose(RxLifecycleAndroid.bindActivity(lifecycle)).test(); lifecycle.onNext(ActivityEvent.RESUME); createObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(RxLifecycleAndroid.bindActivity(lifecycle)).test(); lifecycle.onNext(ActivityEvent.PAUSE); createObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(RxLifecycleAndroid.bindActivity(lifecycle)).test(); lifecycle.onNext(ActivityEvent.STOP); createObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(RxLifecycleAndroid.bindActivity(lifecycle)).test(); lifecycle.onNext(ActivityEvent.DESTROY); createObserver.assertComplete(); stopObserver.assertComplete(); } @Test public void testEndsImmediatelyOutsideActivityLifecycle() { BehaviorSubject lifecycle = BehaviorSubject.create(); lifecycle.onNext(ActivityEvent.DESTROY); TestObserver testObserver = observable.compose(RxLifecycleAndroid.bindActivity(lifecycle)).test(); testObserver.assertComplete(); } @Test public void testBindFragmentLifecycle() { BehaviorSubject lifecycle = BehaviorSubject.create(); lifecycle.onNext(FragmentEvent.ATTACH); TestObserver attachObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); lifecycle.onNext(FragmentEvent.CREATE); attachObserver.assertNotComplete(); TestObserver createObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); lifecycle.onNext(FragmentEvent.CREATE_VIEW); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); TestObserver createViewObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); lifecycle.onNext(FragmentEvent.START); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); TestObserver startObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); lifecycle.onNext(FragmentEvent.RESUME); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); lifecycle.onNext(FragmentEvent.PAUSE); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); lifecycle.onNext(FragmentEvent.STOP); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); lifecycle.onNext(FragmentEvent.DESTROY_VIEW); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertComplete(); stopObserver.assertComplete(); TestObserver destroyViewObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)) .test(); lifecycle.onNext(FragmentEvent.DESTROY); attachObserver.assertNotComplete(); createObserver.assertComplete(); destroyViewObserver.assertComplete(); TestObserver destroyObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); lifecycle.onNext(FragmentEvent.DETACH); attachObserver.assertComplete(); destroyObserver.assertComplete(); } @Test public void testEndsImmediatelyOutsideFragmentLifecycle() { BehaviorSubject lifecycle = BehaviorSubject.create(); lifecycle.onNext(FragmentEvent.DETACH); TestObserver testObserver = observable.compose(RxLifecycleAndroid.bindFragment(lifecycle)).test(); testObserver.assertComplete(); } @Test public void testBindView() { Activity activity = Robolectric.buildActivity(Activity.class).create().get(); View view = new View(activity); CopyOnWriteArrayList listeners = TestUtil.getAttachStateChangeListeners(view); // Do the attach notification if (listeners != null) { for (View.OnAttachStateChangeListener listener : listeners) { listener.onViewAttachedToWindow(view); } } // Subscribe TestObserver viewAttachObserver = observable.compose(RxLifecycleAndroid.bindView(view)).test(); viewAttachObserver.assertNotComplete(); listeners = TestUtil.getAttachStateChangeListeners(view); assertNotNull(listeners); assertFalse(listeners.isEmpty()); // Now detach for (View.OnAttachStateChangeListener listener : listeners) { listener.onViewDetachedFromWindow(view); } viewAttachObserver.assertComplete(); } // Null checks @Test(expected = NullPointerException.class) public void testBindFragmentThrowsOnNull() { //noinspection ResourceType RxLifecycleAndroid.bindFragment(null); } @Test(expected = NullPointerException.class) public void testBindActivityThrowsOnNull() { //noinspection ResourceType RxLifecycleAndroid.bindActivity(null); } @Test(expected = NullPointerException.class) public void testBindViewThrowsOnNullView() { //noinspection ResourceType RxLifecycleAndroid.bindView((View) null); } } ================================================ FILE: rxlifecycle-android/src/test/java/com/trello/rxlifecycle4/TestUtil.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4; import android.view.View; import org.robolectric.util.ReflectionHelpers; import java.util.concurrent.CopyOnWriteArrayList; public class TestUtil { /** * Manually retrieve the view's attach state change listeners of an event. Robolectric * doesn't currently support manually firing these, and it would seem the events are not called * in normal Robolectric usage either. * * @param view View with listeners to notify */ static CopyOnWriteArrayList getAttachStateChangeListeners(View view) { Object listenerInfo = ReflectionHelpers.callInstanceMethod(view, "getListenerInfo"); return ReflectionHelpers.getField(listenerInfo, "mOnAttachStateChangeListeners"); } } ================================================ FILE: rxlifecycle-android-lifecycle/.gitignore ================================================ /build ================================================ FILE: rxlifecycle-android-lifecycle/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion } } repositories { mavenCentral() google() jcenter() } dependencies { api project(':rxlifecycle') implementation rootProject.ext.rxAndroid implementation rootProject.ext.supportAnnotations api rootProject.ext.lifecycle annotationProcessor rootProject.ext.lifecycleProcessor testImplementation rootProject.ext.junit testImplementation rootProject.ext.robolectric testImplementation rootProject.ext.lifecycleExtensions } apply from: "$rootDir/gradle/artifacts.gradle" apply from: "$rootDir/gradle/gradle-mvn-push.gradle" ================================================ FILE: rxlifecycle-android-lifecycle/gradle.properties ================================================ POM_NAME=RxLifecycle-Android-Lifecycle POM_DESCRIPTION=RxLifecycle-Android-Lifecycle POM_ARTIFACT_ID=rxlifecycle-android-lifecycle POM_PACKAGING=aar ================================================ FILE: rxlifecycle-android-lifecycle/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxlifecycle-android-lifecycle/src/main/java/com/trello/lifecycle4/android/lifecycle/AndroidLifecycle.java ================================================ package com.trello.lifecycle4.android.lifecycle; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.OnLifecycleEvent; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; /** * Wraps a {@link LifecycleOwner} so that it can be used as a {@link LifecycleProvider}. For example, * you can do *
{@code
 * LifecycleProvider provider = AndroidLifecycle.createLifecycleProvider(this);
 * myObservable
 *     .compose(provider.bindLifecycle())
 *     .subscribe();
 * }
* where {@code this} is a {@code android.arch.lifecycle.LifecycleActivity} or * {@code android.arch.lifecycle.LifecycleFragment}. */ public final class AndroidLifecycle implements LifecycleProvider, LifecycleObserver { public static LifecycleProvider createLifecycleProvider(LifecycleOwner owner) { return new AndroidLifecycle(owner); } private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); private AndroidLifecycle(LifecycleOwner owner) { owner.getLifecycle().addObserver(this); } @NonNull @Override @CheckResult public Observable lifecycle() { return lifecycleSubject.hide(); } @NonNull @Override @CheckResult public LifecycleTransformer bindUntilEvent(@NonNull Lifecycle.Event event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @NonNull @Override @CheckResult public LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroidLifecycle.bindLifecycle(lifecycleSubject); } @OnLifecycleEvent(Lifecycle.Event.ON_ANY) void onEvent(LifecycleOwner owner, Lifecycle.Event event) { lifecycleSubject.onNext(event); if (event == Lifecycle.Event.ON_DESTROY) { owner.getLifecycle().removeObserver(this); } } } ================================================ FILE: rxlifecycle-android-lifecycle/src/main/java/com/trello/lifecycle4/android/lifecycle/RxLifecycleAndroidLifecycle.java ================================================ package com.trello.lifecycle4.android.lifecycle; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.OutsideLifecycleException; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.lifecycle.Lifecycle; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.functions.Function; import static com.trello.rxlifecycle4.RxLifecycle.bind; public final class RxLifecycleAndroidLifecycle { private RxLifecycleAndroidLifecycle() { throw new AssertionError("No instances"); } /** * Binds the given source to an Android lifecycle. *

* This helper automatically determines (based on the lifecycle sequence itself) when the source * should stop emitting items. In the case that the lifecycle sequence is in the * creation phase (ON_CREATE, ON_START, etc) it will choose the equivalent destructive phase (ON_DESTROY, * ON_STOP, etc). If used in the destructive phase, the notifications will cease at the next event; * for example, if used in ON_PAUSE, it will unsubscribe in ON_STOP. * * @param lifecycle the lifecycle sequence of an Activity * @return a reusable {@link LifecycleTransformer} that unsubscribes the source during the Activity lifecycle */ @NonNull @CheckResult public static LifecycleTransformer bindLifecycle(@NonNull Observable lifecycle) { return bind(lifecycle, LIFECYCLE); } private static final Function LIFECYCLE = new Function() { @Override public Lifecycle.Event apply(Lifecycle.Event lastEvent) throws Exception { switch (lastEvent) { case ON_CREATE: return Lifecycle.Event.ON_DESTROY; case ON_START: return Lifecycle.Event.ON_STOP; case ON_RESUME: return Lifecycle.Event.ON_PAUSE; case ON_PAUSE: return Lifecycle.Event.ON_STOP; case ON_STOP: return Lifecycle.Event.ON_DESTROY; case ON_DESTROY: throw new OutsideLifecycleException("Cannot bind to Activity lifecycle when outside of it."); default: throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented"); } } }; } ================================================ FILE: rxlifecycle-android-lifecycle/src/test/java/com/trello/rxlifecycle4/RxLifecycleTest.java ================================================ package com.trello.rxlifecycle4; import com.trello.lifecycle4.android.lifecycle.RxLifecycleAndroidLifecycle; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import androidx.lifecycle.Lifecycle; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.BehaviorSubject; import io.reactivex.rxjava3.subjects.PublishSubject; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class RxLifecycleTest { private Observable observable; @Before public void setup() { // Simulate an actual lifecycle (hot Observable that does not end) observable = PublishSubject.create().hide(); } @Test public void testBindUntilLifecycleEvent() { BehaviorSubject lifecycle = BehaviorSubject.create(); TestObserver testObserver = observable.compose(RxLifecycle.bindUntilEvent(lifecycle, Lifecycle.Event.ON_STOP)).test(); lifecycle.onNext(Lifecycle.Event.ON_CREATE); testObserver.assertNotComplete(); lifecycle.onNext(Lifecycle.Event.ON_START); testObserver.assertNotComplete(); lifecycle.onNext(Lifecycle.Event.ON_RESUME); testObserver.assertNotComplete(); lifecycle.onNext(Lifecycle.Event.ON_PAUSE); testObserver.assertNotComplete(); lifecycle.onNext(Lifecycle.Event.ON_STOP); testObserver.assertComplete(); } @Test public void testBindLifecycle() { BehaviorSubject lifecycle = BehaviorSubject.create(); lifecycle.onNext(Lifecycle.Event.ON_CREATE); TestObserver createObserver = observable.compose(RxLifecycleAndroidLifecycle.bindLifecycle(lifecycle)).test(); lifecycle.onNext(Lifecycle.Event.ON_START); createObserver.assertNotComplete(); TestObserver startObserver = observable.compose(RxLifecycleAndroidLifecycle.bindLifecycle(lifecycle)).test(); lifecycle.onNext(Lifecycle.Event.ON_RESUME); createObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(RxLifecycleAndroidLifecycle.bindLifecycle(lifecycle)).test(); lifecycle.onNext(Lifecycle.Event.ON_PAUSE); createObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(RxLifecycleAndroidLifecycle.bindLifecycle(lifecycle)).test(); lifecycle.onNext(Lifecycle.Event.ON_STOP); createObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(RxLifecycleAndroidLifecycle.bindLifecycle(lifecycle)).test(); lifecycle.onNext(Lifecycle.Event.ON_DESTROY); createObserver.assertComplete(); stopObserver.assertComplete(); } @Test public void testEndsImmediatelyOutsideLifecycle() { BehaviorSubject lifecycle = BehaviorSubject.create(); lifecycle.onNext(Lifecycle.Event.ON_DESTROY); TestObserver testObserver = observable.compose(RxLifecycleAndroidLifecycle.bindLifecycle(lifecycle)).test(); testObserver.assertComplete(); } // Null checks @Test(expected = NullPointerException.class) public void testBindLifecycleThrowsOnNull() { //noinspection ResourceType RxLifecycleAndroidLifecycle.bindLifecycle(null); } } ================================================ FILE: rxlifecycle-android-lifecycle/src/test/java/com/trello/rxlifecycle4/android/lifecycle/AndroidLifecycleActivityTest.java ================================================ package com.trello.rxlifecycle4.android.lifecycle; import com.trello.lifecycle4.android.lifecycle.AndroidLifecycle; import com.trello.rxlifecycle4.LifecycleProvider; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleOwner; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, sdk = 17) public class AndroidLifecycleActivityTest { private Observable observable; @Before public void setup() { observable = PublishSubject.create().hide(); } @Test public void testLifecycleActivity() { testLifecycle(Robolectric.buildActivity(FragmentActivity.class)); testBindUntilEvent(Robolectric.buildActivity(FragmentActivity.class)); testBindToLifecycle(Robolectric.buildActivity(FragmentActivity.class)); } private void testLifecycle(ActivityController controller) { LifecycleProvider provider = AndroidLifecycle.createLifecycleProvider(controller.get()); TestObserver testObserver = provider.lifecycle().test(); controller.create(); controller.start(); controller.resume(); controller.pause(); controller.stop(); controller.destroy(); testObserver.assertValues( Lifecycle.Event.ON_CREATE, Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME, Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP, Lifecycle.Event.ON_DESTROY ); } // Tests bindUntil for any given AndroidLifecycle Activity implementation private void testBindUntilEvent(ActivityController controller) { LifecycleProvider activity = AndroidLifecycle.createLifecycleProvider(controller.get()); TestObserver testObserver = observable.compose(activity.bindUntilEvent(Lifecycle.Event.ON_STOP)).test(); controller.create(); testObserver.assertNotComplete(); controller.start(); testObserver.assertNotComplete(); controller.resume(); testObserver.assertNotComplete(); controller.pause(); testObserver.assertNotComplete(); controller.stop(); testObserver.assertComplete(); } // Tests bindToLifecycle for any given AndroidLifecycle Activity implementation private void testBindToLifecycle(ActivityController controller) { LifecycleProvider provider = AndroidLifecycle.createLifecycleProvider(controller.get()); controller.create(); TestObserver createObserver = observable.compose(provider.bindToLifecycle()).test(); controller.start(); createObserver.assertNotComplete(); TestObserver startObserver = observable.compose(provider.bindToLifecycle()).test(); controller.resume(); createObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(provider.bindToLifecycle()).test(); controller.pause(); createObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(provider.bindToLifecycle()).test(); controller.stop(); createObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(provider.bindToLifecycle()).test(); controller.destroy(); createObserver.assertComplete(); stopObserver.assertComplete(); } } ================================================ FILE: rxlifecycle-android-lifecycle/src/test/java/com/trello/rxlifecycle4/android/lifecycle/AndroidLifecycleFragmentTest.java ================================================ package com.trello.rxlifecycle4.android.lifecycle; import com.trello.lifecycle4.android.lifecycle.AndroidLifecycle; import com.trello.rxlifecycle4.LifecycleProvider; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleOwner; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class AndroidLifecycleFragmentTest { private Observable observable; @Before public void setup() { observable = PublishSubject.create().hide(); } @Test public void testLifecycleFragment() { testLifecycle(new Fragment()); testBindUntilEvent(new Fragment()); testBindToLifecycle(new Fragment()); } private void testLifecycle(LifecycleOwner owner) { Fragment fragment = (Fragment) owner; ActivityController controller = startFragment(fragment); TestObserver testObserver = AndroidLifecycle.createLifecycleProvider(owner).lifecycle().test(); controller.start(); controller.resume(); controller.pause(); controller.stop(); controller.destroy(); testObserver.assertValues( Lifecycle.Event.ON_CREATE, Lifecycle.Event.ON_START, Lifecycle.Event.ON_RESUME, Lifecycle.Event.ON_PAUSE, Lifecycle.Event.ON_STOP, Lifecycle.Event.ON_DESTROY ); } // Tests bindUntil for any given AndroidLifecycle Fragment implementation private void testBindUntilEvent(LifecycleOwner owner) { Fragment fragment = (Fragment) owner; ActivityController controller = startFragment(fragment); TestObserver testObserver = observable.compose(AndroidLifecycle.createLifecycleProvider(owner).bindUntilEvent(Lifecycle.Event.ON_STOP)).test(); testObserver.assertNotComplete(); controller.start(); testObserver.assertNotComplete(); controller.resume(); testObserver.assertNotComplete(); controller.pause(); testObserver.assertNotComplete(); controller.stop(); testObserver.assertComplete(); } // Tests bindToLifecycle for any given RxLifecycle Fragment implementation private void testBindToLifecycle(LifecycleOwner owner) { Fragment fragment = (Fragment) owner; LifecycleProvider provider = AndroidLifecycle.createLifecycleProvider(owner); ActivityController controller = startFragment(fragment); TestObserver createObserver = observable.compose(provider.bindToLifecycle()).test(); controller.start(); createObserver.assertNotComplete(); TestObserver startObserver = observable.compose(provider.bindToLifecycle()).test(); controller.resume(); createObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(provider.bindToLifecycle()).test(); controller.pause(); createObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(provider.bindToLifecycle()).test(); controller.stop(); createObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(provider.bindToLifecycle()).test(); controller.destroy(); createObserver.assertComplete(); stopObserver.assertComplete(); } // Easier than making everyone create their own shadows private ActivityController startFragment(Fragment fragment) { ActivityController controller = Robolectric.buildActivity(FragmentActivity.class); controller.create(); controller.get().getSupportFragmentManager() .beginTransaction() .add(android.R.id.content, fragment) .commitNow(); return controller; } } ================================================ FILE: rxlifecycle-android-lifecycle-kotlin/.gitignore ================================================ /build ================================================ FILE: rxlifecycle-android-lifecycle-kotlin/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' apply plugin: 'kotlin-android' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion } kotlinOptions { freeCompilerArgs += ["-module-name", "rxlifecycle-android-lifecycle-kotlin-4"] } } repositories { mavenCentral() google() jcenter() } dependencies { implementation kotlinStdlib api project(':rxlifecycle-android-lifecycle') } apply from: "$rootDir/gradle/artifacts.gradle" apply from: "$rootDir/gradle/gradle-mvn-push.gradle" ================================================ FILE: rxlifecycle-android-lifecycle-kotlin/gradle.properties ================================================ POM_NAME=RxLifecycle-Andoird-Lifecycle-kotlin POM_DESCRIPTION=RxLifecycle-Android-Lifecycle-kotlin POM_ARTIFACT_ID=rxlifecycle-android-lifecycle-kotlin POM_PACKAGING=aar ================================================ FILE: rxlifecycle-android-lifecycle-kotlin/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /opt/android-sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: rxlifecycle-android-lifecycle-kotlin/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxlifecycle-android-lifecycle-kotlin/src/main/java/com/trello/rxlifecycle4/android/lifecycle/kotlin/rxlifecycle.kt ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.android.lifecycle.kotlin import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import com.trello.lifecycle4.android.lifecycle.AndroidLifecycle import io.reactivex.rxjava3.core.* fun Observable.bindToLifecycle(owner: LifecycleOwner): Observable = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindToLifecycle()) fun Observable.bindUntilEvent(owner: LifecycleOwner, event: Lifecycle.Event): Observable = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindUntilEvent(event)) fun Flowable.bindToLifecycle(owner: LifecycleOwner): Flowable = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindToLifecycle()) fun Flowable.bindUntilEvent(owner: LifecycleOwner, event: Lifecycle.Event): Flowable = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindUntilEvent(event)) fun Single.bindToLifecycle(owner: LifecycleOwner): Single = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindToLifecycle()) fun Single.bindUntilEvent(owner: LifecycleOwner, event: Lifecycle.Event): Single = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindUntilEvent(event)) fun Maybe.bindToLifecycle(owner: LifecycleOwner): Maybe = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindToLifecycle()) fun Maybe.bindUntilEvent(owner: LifecycleOwner, event: Lifecycle.Event): Maybe = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindUntilEvent(event)) fun Completable.bindToLifecycle(owner: LifecycleOwner): Completable = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindToLifecycle()) fun Completable.bindUntilEvent(owner: LifecycleOwner, event: Lifecycle.Event): Completable = this.compose(AndroidLifecycle.createLifecycleProvider(owner).bindUntilEvent(event)) ================================================ FILE: rxlifecycle-android-lifecycle-kotlin/src/main/res/values/strings.xml ================================================ rxlifecycle-android-lifecycle-kotlin ================================================ FILE: rxlifecycle-components/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion } } repositories { mavenCentral() google() jcenter() } dependencies { api project(':rxlifecycle-android') implementation rootProject.ext.rxJava implementation rootProject.ext.appCompat testImplementation rootProject.ext.junit testImplementation rootProject.ext.robolectric } apply from: "$rootDir/gradle/artifacts.gradle" apply from: "$rootDir/gradle/gradle-mvn-push.gradle" ================================================ FILE: rxlifecycle-components/gradle.properties ================================================ POM_NAME=RxLifecycle-Components POM_DESCRIPTION=RxLifecycle-Components POM_ARTIFACT_ID=rxlifecycle-components POM_PACKAGING=aar ================================================ FILE: rxlifecycle-components/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/RxActivity.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components; import android.app.Activity; import android.os.Bundle; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.ActivityEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxActivity extends Activity implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull ActivityEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindActivity(lifecycleSubject); } @Override @CallSuper protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(ActivityEvent.CREATE); } @Override @CallSuper protected void onStart() { super.onStart(); lifecycleSubject.onNext(ActivityEvent.START); } @Override @CallSuper protected void onResume() { super.onResume(); lifecycleSubject.onNext(ActivityEvent.RESUME); } @Override @CallSuper protected void onPause() { lifecycleSubject.onNext(ActivityEvent.PAUSE); super.onPause(); } @Override @CallSuper protected void onStop() { lifecycleSubject.onNext(ActivityEvent.STOP); super.onStop(); } @Override @CallSuper protected void onDestroy() { lifecycleSubject.onNext(ActivityEvent.DESTROY); super.onDestroy(); } } ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/RxDialogFragment.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components; import android.app.DialogFragment; import android.os.Bundle; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxDialogFragment extends DialogFragment implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/RxFragment.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components; import android.app.Fragment; import android.os.Bundle; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxFragment extends Fragment implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/RxPreferenceFragment.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components; import android.os.Bundle; import android.preference.PreferenceFragment; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxPreferenceFragment extends PreferenceFragment implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/support/RxAppCompatActivity.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.support; import android.os.Bundle; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.ContentView; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.ActivityEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxAppCompatActivity extends AppCompatActivity implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); public RxAppCompatActivity() { super(); } @ContentView public RxAppCompatActivity(@LayoutRes int contentLayoutId) { super(contentLayoutId); } @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull ActivityEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindActivity(lifecycleSubject); } @Override @CallSuper protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(ActivityEvent.CREATE); } @Override @CallSuper protected void onStart() { super.onStart(); lifecycleSubject.onNext(ActivityEvent.START); } @Override @CallSuper protected void onResume() { super.onResume(); lifecycleSubject.onNext(ActivityEvent.RESUME); } @Override @CallSuper protected void onPause() { lifecycleSubject.onNext(ActivityEvent.PAUSE); super.onPause(); } @Override @CallSuper protected void onStop() { lifecycleSubject.onNext(ActivityEvent.STOP); super.onStop(); } @Override @CallSuper protected void onDestroy() { lifecycleSubject.onNext(ActivityEvent.DESTROY); super.onDestroy(); } } ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/support/RxAppCompatDialogFragment.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.support; import android.os.Bundle; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatDialogFragment; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxAppCompatDialogFragment extends AppCompatDialogFragment implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/support/RxDialogFragment.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.support; import android.os.Bundle; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxDialogFragment extends DialogFragment implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/support/RxFragment.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.support; import android.os.Bundle; import android.view.View; import androidx.annotation.CheckResult; import androidx.annotation.ContentView; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxFragment extends Fragment implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); public RxFragment() { super(); } @ContentView public RxFragment(@LayoutRes int contentLayoutId) { super(contentLayoutId); } @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components/src/main/java/com/trello/rxlifecycle4/components/support/RxFragmentActivity.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.support; import android.os.Bundle; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.ContentView; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.FragmentActivity; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.ActivityEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxFragmentActivity extends FragmentActivity implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); public RxFragmentActivity() { super(); } @ContentView public RxFragmentActivity(@LayoutRes int contentLayoutId) { super(contentLayoutId); } @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull ActivityEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindActivity(lifecycleSubject); } @Override @CallSuper protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(ActivityEvent.CREATE); } @Override @CallSuper protected void onStart() { super.onStart(); lifecycleSubject.onNext(ActivityEvent.START); } @Override @CallSuper protected void onResume() { super.onResume(); lifecycleSubject.onNext(ActivityEvent.RESUME); } @Override @CallSuper protected void onPause() { lifecycleSubject.onNext(ActivityEvent.PAUSE); super.onPause(); } @Override @CallSuper protected void onStop() { lifecycleSubject.onNext(ActivityEvent.STOP); super.onStop(); } @Override @CallSuper protected void onDestroy() { lifecycleSubject.onNext(ActivityEvent.DESTROY); super.onDestroy(); } } ================================================ FILE: rxlifecycle-components/src/test/java/com/trello/rxlifecycle4/components/RxActivityLifecycleTest.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.android.ActivityEvent; import com.trello.rxlifecycle4.components.support.RxFragmentActivity; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import org.robolectric.annotation.Config; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; import static com.trello.rxlifecycle4.android.ActivityEvent.STOP; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class RxActivityLifecycleTest { private Observable observable; @Before public void setup() { observable = PublishSubject.create().hide(); } @Test public void testRxActivity() { testLifecycle(Robolectric.buildActivity(TestRxActivity.class)); testBindUntilEvent(Robolectric.buildActivity(TestRxActivity.class)); testBindToLifecycle(Robolectric.buildActivity(TestRxActivity.class)); } @Test public void testRxFragmentActivity() { testLifecycle(Robolectric.buildActivity(TestRxFragmentActivity.class)); testBindUntilEvent(Robolectric.buildActivity(TestRxFragmentActivity.class)); testBindToLifecycle(Robolectric.buildActivity(TestRxFragmentActivity.class)); } @Test public void testRxAppCompatActivity() { // TODO: Doesn't work due to https://github.com/robolectric/robolectric/issues/1796 // // testBindUntilEvent(Robolectric.buildActivity(RxAppCompatActivity.class)); // testBindToLifecycle(Robolectric.buildActivity(RxAppCompatActivity.class)); } private void testLifecycle(ActivityController> controller) { LifecycleProvider activity = controller.get(); TestObserver testObserver = activity.lifecycle().test(); controller.create(); controller.start(); controller.resume(); controller.pause(); controller.stop(); controller.destroy(); testObserver.assertValues( ActivityEvent.CREATE, ActivityEvent.START, ActivityEvent.RESUME, ActivityEvent.PAUSE, ActivityEvent.STOP, ActivityEvent.DESTROY ); } // Tests bindUntil for any given RxActivityLifecycle implementation private void testBindUntilEvent(ActivityController> controller) { LifecycleProvider activity = controller.get(); TestObserver testObserver = observable.compose(activity.bindUntilEvent(STOP)).test(); controller.create(); testObserver.assertNotComplete(); controller.start(); testObserver.assertNotComplete(); controller.resume(); testObserver.assertNotComplete(); controller.pause(); testObserver.assertNotComplete(); controller.stop(); testObserver.assertComplete(); } // Tests bindToLifecycle for any given RxActivityLifecycle implementation private void testBindToLifecycle(ActivityController> controller) { LifecycleProvider activity = controller.get(); controller.create(); TestObserver createObserver = observable.compose(activity.bindToLifecycle()).test(); controller.start(); createObserver.assertNotComplete(); TestObserver startObserver = observable.compose(activity.bindToLifecycle()).test(); controller.resume(); createObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(activity.bindToLifecycle()).test(); controller.pause(); createObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(activity.bindToLifecycle()).test(); controller.stop(); createObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(activity.bindToLifecycle()).test(); controller.destroy(); createObserver.assertComplete(); stopObserver.assertComplete(); } // These classes are just for testing since components are abstract public static class TestRxActivity extends RxActivity { } public static class TestRxFragmentActivity extends RxFragmentActivity{ } } ================================================ FILE: rxlifecycle-components/src/test/java/com/trello/rxlifecycle4/components/RxFragmentLifecycleTest.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components; import android.app.Fragment; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.android.FragmentEvent; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.util.FragmentTestUtil; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; import static com.trello.rxlifecycle4.android.FragmentEvent.STOP; import static org.robolectric.util.FragmentTestUtil.startFragment; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class RxFragmentLifecycleTest { private Observable observable; @Before public void setup() { observable = PublishSubject.create().hide(); } @Test public void testRxFragment() { testLifecycle(new TestRxFragment()); testBindUntilEvent(new TestRxFragment()); testBindToLifecycle(new TestRxFragment()); } @Test public void testRxDialogFragment() { testLifecycle(new TestRxDialogFragment()); testBindUntilEvent(new TestRxDialogFragment()); testBindToLifecycle(new TestRxDialogFragment()); } @Test public void testRxPreferenceFragment() { testLifecycle(new TestRxPreferenceFragment()); testBindUntilEvent(new TestRxPreferenceFragment()); testBindToLifecycle(new TestRxPreferenceFragment()); } private void testLifecycle(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; FragmentTestUtil.startFragment(fragment); TestObserver testObserver = provider.lifecycle().skip(1).test(); fragment.onAttach(null); fragment.onCreate(null); fragment.onViewCreated(null, null); fragment.onStart(); fragment.onResume(); fragment.onPause(); fragment.onStop(); fragment.onDestroyView(); fragment.onDestroy(); fragment.onDetach(); testObserver.assertValues( FragmentEvent.ATTACH, FragmentEvent.CREATE, FragmentEvent.CREATE_VIEW, FragmentEvent.START, FragmentEvent.RESUME, FragmentEvent.PAUSE, FragmentEvent.STOP, FragmentEvent.DESTROY_VIEW, FragmentEvent.DESTROY, FragmentEvent.DETACH ); } // Tests bindUntil for any given LifecycleProvider implementation private void testBindUntilEvent(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; startFragment(fragment); TestObserver testObserver = observable.compose(provider.bindUntilEvent(STOP)).test(); fragment.onAttach(null); testObserver.assertNotComplete(); fragment.onCreate(null); testObserver.assertNotComplete(); fragment.onViewCreated(null, null); testObserver.assertNotComplete(); fragment.onStart(); testObserver.assertNotComplete(); fragment.onResume(); testObserver.assertNotComplete(); fragment.onPause(); testObserver.assertNotComplete(); fragment.onStop(); testObserver.assertComplete(); } // Tests bindToLifecycle for any given LifecycleProvider implementation private void testBindToLifecycle(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; startFragment(fragment); fragment.onAttach(null); TestObserver attachObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onCreate(null); attachObserver.assertNotComplete(); TestObserver createObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onViewCreated(null, null); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); TestObserver createViewObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onStart(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); TestObserver startObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onResume(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onPause(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onStop(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDestroyView(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertComplete(); stopObserver.assertComplete(); TestObserver destroyViewObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDestroy(); attachObserver.assertNotComplete(); createObserver.assertComplete(); destroyViewObserver.assertComplete(); TestObserver destroyObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDetach(); attachObserver.assertComplete(); destroyObserver.assertComplete(); } // These classes are just for testing since components are abstract public static class TestRxFragment extends RxFragment { } public static class TestRxDialogFragment extends RxDialogFragment { } public static class TestRxPreferenceFragment extends RxPreferenceFragment { } } ================================================ FILE: rxlifecycle-components/src/test/java/com/trello/rxlifecycle4/components/support/RxSupportFragmentLifecycleTest.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.support; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.android.FragmentEvent; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; import static com.trello.rxlifecycle4.android.FragmentEvent.STOP; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class RxSupportFragmentLifecycleTest { private Observable observable; @Before public void setup() { observable = PublishSubject.create().hide(); } @Test public void testRxFragment() { testLifecycle(new TestRxFragment()); testBindUntilEvent(new TestRxFragment()); testBindToLifecycle(new TestRxFragment()); } @Test public void testRxDialogFragment() { testLifecycle(new TestRxDialogFragment()); testBindUntilEvent(new TestRxDialogFragment()); testBindToLifecycle(new TestRxDialogFragment()); } @Test public void testRxAppCompatDialogFragment() { // Once Robolectric is less broken we could run these tests // Until then, these are identical to RxDialogFragment, so whatever. // // testLifecycle(new RxAppCompatDialogFragment()); // testBindUntilEvent(new RxAppCompatDialogFragment()); // testBindToLifecycle(new RxAppCompatDialogFragment()); } private void testLifecycle(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; startFragment(fragment); TestObserver testObserver = provider.lifecycle().skip(1).test(); fragment.onAttach(null); fragment.onCreate(null); fragment.onViewCreated(null, null); fragment.onStart(); fragment.onResume(); fragment.onPause(); fragment.onStop(); fragment.onDestroyView(); fragment.onDestroy(); fragment.onDetach(); testObserver.assertValues( FragmentEvent.ATTACH, FragmentEvent.CREATE, FragmentEvent.CREATE_VIEW, FragmentEvent.START, FragmentEvent.RESUME, FragmentEvent.PAUSE, FragmentEvent.STOP, FragmentEvent.DESTROY_VIEW, FragmentEvent.DESTROY, FragmentEvent.DETACH ); } // Tests bindUntil for any given LifecycleProvider implementation private void testBindUntilEvent(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; startFragment(fragment); TestObserver testObserver = observable.compose(provider.bindUntilEvent(STOP)).test(); fragment.onAttach(null); testObserver.assertNotComplete(); fragment.onCreate(null); testObserver.assertNotComplete(); fragment.onViewCreated(null, null); testObserver.assertNotComplete(); fragment.onStart(); testObserver.assertNotComplete(); fragment.onResume(); testObserver.assertNotComplete(); fragment.onPause(); testObserver.assertNotComplete(); fragment.onStop(); testObserver.assertComplete(); } // Tests bindToLifecycle for any given LifecycleProvider implementation private void testBindToLifecycle(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; startFragment(fragment); fragment.onAttach(null); TestObserver attachObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onCreate(null); attachObserver.assertNotComplete(); TestObserver createObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onViewCreated(null, null); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); TestObserver createViewObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onStart(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); TestObserver startObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onResume(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onPause(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onStop(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDestroyView(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertComplete(); stopObserver.assertComplete(); TestObserver destroyViewObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDestroy(); attachObserver.assertNotComplete(); createObserver.assertComplete(); destroyViewObserver.assertComplete(); TestObserver destroyObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDetach(); attachObserver.assertComplete(); destroyObserver.assertComplete(); } // Easier than making everyone create their own shadows private void startFragment(Fragment fragment) { Robolectric.setupActivity(FragmentActivity.class).getSupportFragmentManager() .beginTransaction() .add(fragment, null) .commit(); } // These classes are just for testing since components are abstract public static class TestRxFragment extends RxFragment { } public static class TestRxDialogFragment extends RxDialogFragment { } } ================================================ FILE: rxlifecycle-components-preference/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion } } repositories { mavenCentral() google() jcenter() } dependencies { api project(':rxlifecycle-android') implementation rootProject.ext.rxJava implementation rootProject.ext.preferenceCompat testImplementation rootProject.ext.junit testImplementation rootProject.ext.robolectric } apply from: "$rootDir/gradle/artifacts.gradle" apply from: "$rootDir/gradle/gradle-mvn-push.gradle" ================================================ FILE: rxlifecycle-components-preference/gradle.properties ================================================ POM_NAME=RxLifecycle-Components-Preference POM_DESCRIPTION=RxLifecycle-Components-Preference POM_ARTIFACT_ID=rxlifecycle-components-preference POM_PACKAGING=aar ================================================ FILE: rxlifecycle-components-preference/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxlifecycle-components-preference/src/main/java/com/trello/rxlifecycle4/components/preference/RxEditTextPreferenceDialogFragmentCompat.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.preference; import android.os.Bundle; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.preference.EditTextPreferenceDialogFragmentCompat; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxEditTextPreferenceDialogFragmentCompat extends EditTextPreferenceDialogFragmentCompat implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components-preference/src/main/java/com/trello/rxlifecycle4/components/preference/RxListPreferenceDialogFragmentCompat.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.preference; import android.os.Bundle; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.preference.ListPreferenceDialogFragmentCompat; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxListPreferenceDialogFragmentCompat extends ListPreferenceDialogFragmentCompat implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components-preference/src/main/java/com/trello/rxlifecycle4/components/preference/RxPreferenceDialogFragmentCompat.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.preference; import android.os.Bundle; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.preference.PreferenceDialogFragmentCompat; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxPreferenceDialogFragmentCompat extends PreferenceDialogFragmentCompat implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components-preference/src/main/java/com/trello/rxlifecycle4/components/preference/RxPreferenceFragmentCompat.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.preference; import android.os.Bundle; import android.view.View; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.LifecycleTransformer; import com.trello.rxlifecycle4.RxLifecycle; import com.trello.rxlifecycle4.android.FragmentEvent; import com.trello.rxlifecycle4.android.RxLifecycleAndroid; import androidx.annotation.CallSuper; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.preference.PreferenceFragmentCompat; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.subjects.BehaviorSubject; public abstract class RxPreferenceFragmentCompat extends PreferenceFragmentCompat implements LifecycleProvider { private final BehaviorSubject lifecycleSubject = BehaviorSubject.create(); @Override @NonNull @CheckResult public final Observable lifecycle() { return lifecycleSubject.hide(); } @Override @NonNull @CheckResult public final LifecycleTransformer bindUntilEvent(@NonNull FragmentEvent event) { return RxLifecycle.bindUntilEvent(lifecycleSubject, event); } @Override @NonNull @CheckResult public final LifecycleTransformer bindToLifecycle() { return RxLifecycleAndroid.bindFragment(lifecycleSubject); } @Override @CallSuper public void onAttach(android.app.Activity activity) { super.onAttach(activity); lifecycleSubject.onNext(FragmentEvent.ATTACH); } @Override @CallSuper public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE); } @Override @CallSuper public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW); } @Override @CallSuper public void onStart() { super.onStart(); lifecycleSubject.onNext(FragmentEvent.START); } @Override @CallSuper public void onResume() { super.onResume(); lifecycleSubject.onNext(FragmentEvent.RESUME); } @Override @CallSuper public void onPause() { lifecycleSubject.onNext(FragmentEvent.PAUSE); super.onPause(); } @Override @CallSuper public void onStop() { lifecycleSubject.onNext(FragmentEvent.STOP); super.onStop(); } @Override @CallSuper public void onDestroyView() { lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW); super.onDestroyView(); } @Override @CallSuper public void onDestroy() { lifecycleSubject.onNext(FragmentEvent.DESTROY); super.onDestroy(); } @Override @CallSuper public void onDetach() { lifecycleSubject.onNext(FragmentEvent.DETACH); super.onDetach(); } } ================================================ FILE: rxlifecycle-components-preference/src/test/java/com/trello/rxlifecycle4/components/preference/RxPreferenceFragmentLifecycleTest.java ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.components.preference; import android.os.Bundle; import com.trello.rxlifecycle4.LifecycleProvider; import com.trello.rxlifecycle4.android.FragmentEvent; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.subjects.PublishSubject; import static com.trello.rxlifecycle4.android.FragmentEvent.STOP; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class RxPreferenceFragmentLifecycleTest { private Observable observable; @Before public void setup() { observable = PublishSubject.create().hide(); } @Test public void testRxPreferenceFragmentCompat() { // Requires android.support.v7.preference.R.preferenceTheme // attribute being set. // // testLifecycle(new TestRxPreferenceFragmentCompat()); // testBindUntilEvent(new TestRxPreferenceFragmentCompat()); // testBindToLifecycle(new TestRxPreferenceFragmentCompat()); } private void testLifecycle(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; startFragment(fragment); TestObserver testObserver = provider.lifecycle().skip(1).test(); fragment.onAttach(null); fragment.onCreate(null); fragment.onViewCreated(null, null); fragment.onStart(); fragment.onResume(); fragment.onPause(); fragment.onStop(); fragment.onDestroyView(); fragment.onDestroy(); fragment.onDetach(); testObserver.assertValues( FragmentEvent.ATTACH, FragmentEvent.CREATE, FragmentEvent.CREATE_VIEW, FragmentEvent.START, FragmentEvent.RESUME, FragmentEvent.PAUSE, FragmentEvent.STOP, FragmentEvent.DESTROY_VIEW, FragmentEvent.DESTROY, FragmentEvent.DETACH ); } // Tests bindUntil for any given LifecycleProvider implementation private void testBindUntilEvent(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; startFragment(fragment); TestObserver testObserver = observable.compose(provider.bindUntilEvent(STOP)).test(); fragment.onAttach(null); testObserver.assertNotComplete(); fragment.onCreate(null); testObserver.assertNotComplete(); fragment.onViewCreated(null, null); testObserver.assertNotComplete(); fragment.onStart(); testObserver.assertNotComplete(); fragment.onResume(); testObserver.assertNotComplete(); fragment.onPause(); testObserver.assertNotComplete(); fragment.onStop(); testObserver.assertComplete(); } // Tests bindToLifecycle for any given LifecycleProvider implementation private void testBindToLifecycle(LifecycleProvider provider) { Fragment fragment = (Fragment) provider; startFragment(fragment); fragment.onAttach(null); TestObserver attachObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onCreate(null); attachObserver.assertNotComplete(); TestObserver createObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onViewCreated(null, null); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); TestObserver createViewObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onStart(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); TestObserver startObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onResume(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertNotComplete(); TestObserver resumeObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onPause(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertNotComplete(); resumeObserver.assertComplete(); TestObserver pauseObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onStop(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertNotComplete(); startObserver.assertComplete(); pauseObserver.assertComplete(); TestObserver stopObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDestroyView(); attachObserver.assertNotComplete(); createObserver.assertNotComplete(); createViewObserver.assertComplete(); stopObserver.assertComplete(); TestObserver destroyViewObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDestroy(); attachObserver.assertNotComplete(); createObserver.assertComplete(); destroyViewObserver.assertComplete(); TestObserver destroyObserver = observable.compose(provider.bindToLifecycle()).test(); fragment.onDetach(); attachObserver.assertComplete(); destroyObserver.assertComplete(); } // Easier than making everyone create their own shadows private void startFragment(Fragment fragment) { Robolectric.setupActivity(FragmentActivity.class).getSupportFragmentManager() .beginTransaction() .add(fragment, null) .commit(); } // These classes are just for testing since components are abstract public static class TestRxPreferenceFragmentCompat extends RxPreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle bundle, String s) { } } } ================================================ FILE: rxlifecycle-kotlin/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' apply plugin: 'kotlin-android' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion } kotlinOptions { freeCompilerArgs += ["-module-name", "rxlifecycle-kotlin-4"] } } repositories { mavenCentral() google() jcenter() } dependencies { implementation kotlinStdlib api project(':rxlifecycle-android') } apply from: "$rootDir/gradle/artifacts.gradle" apply from: "$rootDir/gradle/gradle-mvn-push.gradle" ================================================ FILE: rxlifecycle-kotlin/gradle.properties ================================================ POM_NAME=RxLifecycle-kotlin POM_DESCRIPTION=RxLifecycle-kotlin POM_ARTIFACT_ID=rxlifecycle-kotlin POM_PACKAGING=aar ================================================ FILE: rxlifecycle-kotlin/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxlifecycle-kotlin/src/main/java/com/trello/rxlifecycle4/kotlin/rxlifecycle.kt ================================================ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.kotlin import android.view.View import com.trello.rxlifecycle4.LifecycleProvider import com.trello.rxlifecycle4.RxLifecycle import com.trello.rxlifecycle4.android.RxLifecycleAndroid import io.reactivex.rxjava3.core.* import io.reactivex.rxjava3.functions.Function // RxLifecycle extensions fun Observable.bind(lifecycle: Observable): Observable = this.compose(RxLifecycle.bind(lifecycle)) fun Observable.bindUntilEvent(lifecycle: Observable, event: E): Observable = this.compose(RxLifecycle.bindUntilEvent(lifecycle, event)) fun Observable.bind(lifecycle: Observable, correspondingEvents: Function): Observable = this.compose(RxLifecycle.bind(lifecycle, correspondingEvents)) fun Flowable.bind(lifecycle: Observable): Flowable = this.compose(RxLifecycle.bind(lifecycle)) fun Flowable.bindUntilEvent(lifecycle: Observable, event: E): Flowable = this.compose(RxLifecycle.bindUntilEvent(lifecycle, event)) fun Flowable.bind(lifecycle: Observable, correspondingEvents: Function): Flowable = this.compose(RxLifecycle.bind(lifecycle, correspondingEvents)) fun Single.bind(lifecycle: Observable): Single = this.compose(RxLifecycle.bind(lifecycle)) fun Single.bindUntilEvent(lifecycle: Observable, event: E): Single = this.compose(RxLifecycle.bindUntilEvent(lifecycle, event)) fun Single.bind(lifecycle: Observable, correspondingEvents: Function): Single = this.compose(RxLifecycle.bind(lifecycle, correspondingEvents)) fun Maybe.bind(lifecycle: Observable): Maybe = this.compose(RxLifecycle.bind(lifecycle)) fun Maybe.bindUntilEvent(lifecycle: Observable, event: E): Maybe = this.compose(RxLifecycle.bindUntilEvent(lifecycle, event)) fun Maybe.bind(lifecycle: Observable, correspondingEvents: Function): Maybe = this.compose(RxLifecycle.bind(lifecycle, correspondingEvents)) fun Completable.bind(lifecycle: Observable): Completable = this.compose(RxLifecycle.bind(lifecycle)) fun Completable.bindUntilEvent(lifecycle: Observable, event: E): Completable = this.compose(RxLifecycle.bindUntilEvent(lifecycle, event)) fun Completable.bind(lifecycle: Observable, correspondingEvents: Function): Completable = this.compose(RxLifecycle.bind(lifecycle, correspondingEvents)) // RxLifecycleAndroid extensions fun Observable.bindToLifecycle(provider: LifecycleProvider): Observable = this.compose(provider.bindToLifecycle()) fun Observable.bindUntilEvent(provider: LifecycleProvider, event: E): Observable = this.compose(provider.bindUntilEvent(event)) fun Observable.bindToLifecycle(view: View): Observable = this.compose(RxLifecycleAndroid.bindView(view)) fun Flowable.bindToLifecycle(provider: LifecycleProvider): Flowable = this.compose(provider.bindToLifecycle()) fun Flowable.bindUntilEvent(provider: LifecycleProvider, event: E): Flowable = this.compose(provider.bindUntilEvent(event)) fun Flowable.bindToLifecycle(view: View): Flowable = this.compose(RxLifecycleAndroid.bindView(view)) fun Single.bindToLifecycle(provider: LifecycleProvider): Single = this.compose(provider.bindToLifecycle()) fun Single.bindUntilEvent(provider: LifecycleProvider, event: E): Single = this.compose(provider.bindUntilEvent(event)) fun Single.bindToLifecycle(view: View): Single = this.compose(RxLifecycleAndroid.bindView(view)) fun Maybe.bindToLifecycle(provider: LifecycleProvider): Maybe = this.compose(provider.bindToLifecycle()) fun Maybe.bindUntilEvent(provider: LifecycleProvider, event: E): Maybe = this.compose(provider.bindUntilEvent(event)) fun Maybe.bindToLifecycle(view: View): Maybe = this.compose(RxLifecycleAndroid.bindView(view)) fun Completable.bindToLifecycle(provider: LifecycleProvider): Completable = this.compose(provider.bindToLifecycle()) fun Completable.bindUntilEvent(provider: LifecycleProvider, event: E): Completable = this.compose(provider.bindUntilEvent(event)) fun Completable.bindToLifecycle(view: View): Completable = this.compose(RxLifecycleAndroid.bindView(view)) ================================================ FILE: rxlifecycle-sample/build.gradle ================================================ apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { applicationId "com.trello.rxlifecycle4.sample" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } sourceSets { main.java.srcDirs += 'src/main/kotlin' } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } repositories { mavenCentral() google() jcenter() } dependencies { implementation project(':rxlifecycle-components') implementation project(':rxlifecycle-kotlin') implementation rootProject.ext.appCompat implementation rootProject.ext.kotlinStdlib } ================================================ FILE: rxlifecycle-sample/src/main/AndroidManifest.xml ================================================ ================================================ FILE: rxlifecycle-sample/src/main/java/com/trello/rxlifecycle4/sample/MainActivity.java ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.sample; import android.os.Bundle; import android.util.Log; import com.trello.rxlifecycle4.android.ActivityEvent; import com.trello.rxlifecycle4.components.support.RxAppCompatActivity; import java.util.concurrent.TimeUnit; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.functions.Action; import io.reactivex.rxjava3.functions.Consumer; public class MainActivity extends RxAppCompatActivity { private static final String TAG = "RxLifecycleAndroid"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate()"); setContentView(R.layout.activity_main); // Specifically bind this until onPause() Observable.interval(1, TimeUnit.SECONDS) .doOnDispose(new Action() { @Override public void run() throws Exception { Log.i(TAG, "Unsubscribing subscription from onCreate()"); } }) .compose(this.bindUntilEvent(ActivityEvent.PAUSE)) .subscribe(new Consumer() { @Override public void accept(Long num) throws Exception { Log.i(TAG, "Started in onCreate(), running until onPause(): " + num); } }); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart()"); // Using automatic unsubscription, this should determine that the correct time to // unsubscribe is onStop (the opposite of onStart). Observable.interval(1, TimeUnit.SECONDS) .doOnDispose(new Action() { @Override public void run() throws Exception { Log.i(TAG, "Unsubscribing subscription from onStart()"); } }) .compose(this.bindToLifecycle()) .subscribe(new Consumer() { @Override public void accept(Long num) throws Exception { Log.i(TAG, "Started in onStart(), running until in onStop(): " + num); } }); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume()"); // `this.` is necessary if you're compiling on JDK7 or below. // // If you're using JDK8+, then you can safely remove it. Observable.interval(1, TimeUnit.SECONDS) .doOnDispose(new Action() { @Override public void run() throws Exception { Log.i(TAG, "Unsubscribing subscription from onResume()"); } }) .compose(this.bindUntilEvent(ActivityEvent.DESTROY)) .subscribe(new Consumer() { @Override public void accept(Long num) throws Exception { Log.i(TAG, "Started in onResume(), running until in onDestroy(): " + num); } }); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause()"); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop()"); } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy()"); } } ================================================ FILE: rxlifecycle-sample/src/main/kotlin/com/trello/rxlifecycle4/sample/KotlinActivity.kt ================================================ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.rxlifecycle4.sample import android.os.Bundle import android.util.Log import com.trello.rxlifecycle4.android.ActivityEvent import com.trello.rxlifecycle4.components.support.RxAppCompatActivity import com.trello.rxlifecycle4.kotlin.bindToLifecycle import com.trello.rxlifecycle4.kotlin.bindUntilEvent import io.reactivex.rxjava3.core.Observable import java.util.concurrent.TimeUnit class KotlinActivity : RxAppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate()") setContentView(R.layout.activity_main) // Specifically bind this until onPause() Observable.interval(1, TimeUnit.SECONDS) .doOnDispose { Log.i(TAG, "Unsubscribing subscription from onCreate()") } .bindUntilEvent(this, ActivityEvent.PAUSE) .subscribe { num -> Log.i(TAG, "Started in onCreate(), running until onPause(): " + num) } } override fun onStart() { super.onStart() Log.d(TAG, "onStart()") // Using automatic unsubscription, this should determine that the correct time to // unsubscribe is onStop (the opposite of onStart). Observable.interval(1, TimeUnit.SECONDS) .doOnDispose { Log.i(TAG, "Unsubscribing subscription from onStart()") } .bindToLifecycle(this) .subscribe { num -> Log.i(TAG, "Started in onStart(), running until in onStop(): " + num) } } override fun onResume() { super.onResume() Log.d(TAG, "onResume()") Observable.interval(1, TimeUnit.SECONDS) .doOnDispose { Log.i(TAG, "Unsubscribing subscription from onResume()") } .bindUntilEvent(this, ActivityEvent.DESTROY) .subscribe { num -> Log.i(TAG, "Started in onResume(), running until in onDestroy(): " + num) } } override fun onPause() { super.onPause() Log.d(TAG, "onPause()") } override fun onStop() { super.onStop() Log.d(TAG, "onStop()") } override fun onDestroy() { super.onDestroy() Log.d(TAG, "onDestroy()") } companion object { private val TAG = "RxLifecycle-Kotlin" } } ================================================ FILE: rxlifecycle-sample/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: rxlifecycle-sample/src/main/res/values/dimens.xml ================================================ 16dp 16dp ================================================ FILE: rxlifecycle-sample/src/main/res/values/strings.xml ================================================ RxLifecycle RxLifecycle (Kotlin) Check logcat tag "RxLifecycle" to see this sample in action. You\'ll need to finish the Activity (or recreate it) to see the automatic unsubscription in action. ================================================ FILE: settings.gradle ================================================ include ':rxlifecycle' include ':rxlifecycle-android' include ':rxlifecycle-android-lifecycle' include ':rxlifecycle-android-lifecycle-kotlin' include ':rxlifecycle-components' include ':rxlifecycle-components-preference' include ':rxlifecycle-kotlin' include ':rxlifecycle-sample'