├── .gitignore
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── futurice
│ │ └── rxmvvmdi
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── futurice
│ │ │ └── rxmvvmdi
│ │ │ ├── RxMvvmApp.java
│ │ │ ├── activities
│ │ │ ├── ListBindingExampleActivity.java
│ │ │ ├── MainActivity.java
│ │ │ ├── MvvmActivity.java
│ │ │ ├── RxBindingExampleActivity.java
│ │ │ ├── RxPropertyExampleActivity.java
│ │ │ └── StaticBindingExampleActivity.java
│ │ │ ├── dagger
│ │ │ ├── ActivityScope.java
│ │ │ ├── components
│ │ │ │ ├── ActivityComponent.java
│ │ │ │ └── AppComponent.java
│ │ │ └── modules
│ │ │ │ ├── ActivityModule.java
│ │ │ │ └── AppModule.java
│ │ │ ├── models
│ │ │ ├── Post.java
│ │ │ └── User.java
│ │ │ ├── services
│ │ │ ├── IBackendService.java
│ │ │ ├── NavigatorService.java
│ │ │ └── SystemMonitorService.java
│ │ │ └── viewmodels
│ │ │ ├── ListBindingExampleViewModel.java
│ │ │ ├── MainViewModel.java
│ │ │ ├── RxBindingExampleViewModel.java
│ │ │ ├── RxProperty.java
│ │ │ ├── RxPropertyExampleViewModel.java
│ │ │ ├── StaticBindingExampleViewModel.java
│ │ │ └── ViewModel.java
│ └── res
│ │ ├── layout
│ │ ├── activity_list_binding_example.xml
│ │ ├── activity_main.xml
│ │ ├── activity_rx_binding_example.xml
│ │ ├── activity_rx_property_example.xml
│ │ ├── activity_static_binding_example.xml
│ │ └── item_post.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── futurice
│ └── rxmvvmdi
│ ├── DelegatingTestScheduler.java
│ ├── RxTest.java
│ └── viewmodels
│ ├── MainActivityViewModelTest.java
│ └── RxBindingExampleViewModelTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── set-branch.png
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | /.idea
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # android-rxmvvmdi
2 | Project for introducing Android developers to how one can combine Rx, MVVM, DI, data-binding, and unit testing concepts. Each activity introduces a certain set of concepts which are documented in the activity class itself.
3 |
4 | ## Setup
5 | ### JDK8
6 | This project uses retrolambda, so you need to make sure to have [JDK8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) installed and the JAVA8_HOME environment variable set to point to it.
7 |
8 | ### Android Studio & Gradle
9 | Android Studio >= v2.1 recommended. May work with earlier versions, but you might run into issues with the combination of data-binding libraries, retrolambda, and dagger that uses android-apt. The project depends on android build tools v2.0.0, it does not build with v2.1.0.
10 |
11 | ## Exercises
12 | To view the exercises, switch to the `start-exercises` branch and read the README.md file. That branch contains code which has been modified by removing code that needs to be recreated. You can treat the master branch as the reference implementation for the answers of the exercises.
13 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'me.tatarka.retrolambda'
3 |
4 | android {
5 | compileSdkVersion 23
6 | buildToolsVersion "23.0.3"
7 |
8 | compileOptions {
9 | // For retrolambda. Need to install JDK8 and set JAVA8_HOME variable
10 | sourceCompatibility JavaVersion.VERSION_1_8
11 | targetCompatibility JavaVersion.VERSION_1_8
12 | }
13 | defaultConfig {
14 | applicationId "com.futurice.rxmvvmdi"
15 | minSdkVersion 21
16 | targetSdkVersion 23
17 | versionCode 1
18 | versionName "1.0"
19 | }
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 | dataBinding {
27 | // Android data-binding
28 | enabled = true
29 | }
30 | }
31 |
32 | dependencies {
33 | compile fileTree(dir: 'libs', include: ['*.jar'])
34 | testCompile (
35 | 'junit:junit:4.12',
36 | 'org.mockito:mockito-core:2.0.5-beta'
37 | )
38 | compile (
39 | 'com.android.support:appcompat-v7:23.3.0',
40 |
41 | // Rx
42 | 'io.reactivex:rxjava:1.1.+',
43 | 'io.reactivex:rxandroid:1.1.+',
44 | 'io.reactivex:rxjava-math:1.0.+',
45 |
46 | // DI
47 | 'com.google.dagger:dagger:2.2',
48 |
49 | // Java8 date APIs
50 | 'com.jakewharton.threetenabp:threetenabp:1.0.+',
51 |
52 | // Retrofit and GSON for backend calls, and stetho for debugging them
53 | 'com.squareup.retrofit2:retrofit:2.0.+',
54 | 'com.squareup.retrofit2:converter-gson:2.0.+',
55 | 'com.squareup.retrofit2:adapter-rxjava:2.0.+',
56 | 'com.facebook.stetho:stetho:1.3.+',
57 | 'com.facebook.stetho:stetho-okhttp3:1.3.+',
58 |
59 | // Collection data binding
60 | 'me.tatarka.bindingcollectionadapter:bindingcollectionadapter:1.2.0-beta1'
61 | )
62 | // DI
63 | provided "com.google.dagger:dagger-compiler:2.2"
64 | }
65 |
66 | retrolambda {
67 | javaVersion JavaVersion.VERSION_1_7
68 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Users\osal\AppData\Local\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/futurice/rxmvvmdi/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/RxMvvmApp.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi;
2 |
3 | import android.app.Application;
4 |
5 | import com.facebook.stetho.Stetho;
6 | import com.futurice.rxmvvmdi.dagger.components.AppComponent;
7 |
8 | /**
9 | * Created by osal on 3.5.2016.
10 | */
11 | public class RxMvvmApp extends Application {
12 | private static AppComponent appComponent;
13 |
14 | @Override
15 | public void onCreate() {
16 | super.onCreate();
17 |
18 | Stetho.initializeWithDefaults(this);
19 |
20 | appComponent = AppComponent.Initializer.init(this);
21 | appComponent.inject(this);
22 | }
23 |
24 | public static AppComponent getAppComponent() {
25 | return appComponent;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/activities/ListBindingExampleActivity.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.activities;
2 |
3 | import android.databinding.DataBindingUtil;
4 | import android.os.Bundle;
5 |
6 | import com.futurice.rxmvvmdi.BR;
7 | import com.futurice.rxmvvmdi.R;
8 | import com.futurice.rxmvvmdi.RxMvvmApp;
9 | import com.futurice.rxmvvmdi.dagger.modules.ActivityModule;
10 | import com.futurice.rxmvvmdi.databinding.ActivityListBindingExampleBinding;
11 | import com.futurice.rxmvvmdi.viewmodels.ListBindingExampleViewModel;
12 | import com.futurice.rxmvvmdi.viewmodels.ViewModel;
13 |
14 | import javax.inject.Inject;
15 |
16 | import me.tatarka.bindingcollectionadapter.ItemView;
17 |
18 | public class ListBindingExampleActivity extends MvvmActivity {
19 |
20 | private ActivityListBindingExampleBinding binding;
21 |
22 | @Inject
23 | ListBindingExampleViewModel viewModel;
24 |
25 | @Override
26 | protected void onCreate(Bundle savedInstanceState) {
27 | super.onCreate(savedInstanceState);
28 |
29 | RxMvvmApp.getAppComponent()
30 | .plusActivity(new ActivityModule(this))
31 | .inject(this);
32 |
33 | binding = DataBindingUtil.setContentView(this, R.layout.activity_list_binding_example);
34 | binding.setVm(viewModel);
35 | binding.setItemViews(new ItemViews());
36 | }
37 |
38 | @Override
39 | protected ViewModel getViewModel() {
40 | return viewModel;
41 | }
42 |
43 | public static class ItemViews {
44 | public final ItemView postItemView = ItemView.of(BR.item, R.layout.item_post);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/activities/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.activities;
2 |
3 | import android.databinding.DataBindingUtil;
4 | import android.os.Bundle;
5 | import android.view.View;
6 |
7 | import com.futurice.rxmvvmdi.R;
8 | import com.futurice.rxmvvmdi.RxMvvmApp;
9 | import com.futurice.rxmvvmdi.dagger.components.ActivityComponent;
10 | import com.futurice.rxmvvmdi.dagger.modules.ActivityModule;
11 | import com.futurice.rxmvvmdi.databinding.ActivityMainBinding;
12 | import com.futurice.rxmvvmdi.viewmodels.MainViewModel;
13 | import com.futurice.rxmvvmdi.viewmodels.ViewModel;
14 |
15 | import javax.inject.Inject;
16 |
17 | /**
18 | * This activity acts as the entry point to the other exercises, but also demonstrates the
19 | * following concepts:
20 | * - using data-binding to add click handlers (click handlers could also be added directly in the
21 | * VM, but that would force having handler function signatures with unnecessary view dependencies)
22 | * - using DI to inject a navigator for starting activities. This avoids a context dependency in the
23 | * VM, making it more testable.
24 | */
25 | public class MainActivity extends MvvmActivity {
26 | private static final String TAG = MainActivity.class.getName();
27 |
28 | private ActivityMainBinding binding;
29 |
30 | @Inject
31 | RxMvvmApp app;
32 |
33 | @Inject
34 | MainViewModel viewModel;
35 |
36 | @Override
37 | protected void onCreate(Bundle savedInstanceState) {
38 | super.onCreate(savedInstanceState);
39 |
40 | ActivityComponent component = RxMvvmApp.getAppComponent().plusActivity(new ActivityModule(this));
41 | component.inject(this);
42 |
43 | binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
44 | binding.setHandlers(new Handlers());
45 | }
46 |
47 | @Override
48 | protected ViewModel getViewModel() {
49 | return viewModel;
50 | }
51 |
52 | public class Handlers {
53 | public void onStaticDataBindingClicked(View view) {
54 | viewModel.selectStaticDataBinding();
55 | }
56 |
57 | public void onRxBindingClicked(View view) {
58 | viewModel.selectRxBinding();
59 | }
60 |
61 | public void onRxPropertyClicked(View view) {
62 | viewModel.selectRxProperty();
63 | }
64 |
65 | public void onListBindingClicked(View view) {
66 | viewModel.selectListBinding();
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/activities/MvvmActivity.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.activities;
2 |
3 | import android.support.annotation.CallSuper;
4 | import android.support.v7.app.AppCompatActivity;
5 |
6 | import com.futurice.rxmvvmdi.viewmodels.ViewModel;
7 |
8 | import rx.subscriptions.CompositeSubscription;
9 |
10 | /**
11 | * Created by osal on 4.5.2016.
12 | */
13 | public abstract class MvvmActivity extends AppCompatActivity {
14 |
15 | private final CompositeSubscription subscriptions = new CompositeSubscription();
16 |
17 | @CallSuper
18 | @Override
19 | public void onAttachedToWindow() {
20 | super.onAttachedToWindow();
21 | getViewModel().bind();
22 | }
23 |
24 | @CallSuper
25 | @Override
26 | public void onDetachedFromWindow() {
27 | super.onDetachedFromWindow();
28 | getViewModel().unbind();
29 | }
30 |
31 | @CallSuper
32 | @Override
33 | public void onResume() {
34 | // Bind view to viewmodel during resume
35 | super.onResume();
36 | subscriptions.clear();
37 | CompositeSubscription newSubscriptions = new CompositeSubscription();
38 | bindView(newSubscriptions);
39 | subscriptions.add(newSubscriptions);
40 | }
41 |
42 | @CallSuper
43 | @Override
44 | public void onPause() {
45 | // Unbind view from viewmodel during pause (avoid unnecessary view updates)
46 | super.onPause();
47 | subscriptions.clear();
48 | }
49 |
50 | protected abstract ViewModel getViewModel();
51 |
52 | protected void bindView(CompositeSubscription subscriptions) {}
53 | }
54 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/activities/RxBindingExampleActivity.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.activities;
2 |
3 | import android.databinding.DataBindingUtil;
4 | import android.support.v7.app.AppCompatActivity;
5 | import android.os.Bundle;
6 | import android.view.View;
7 |
8 | import com.futurice.rxmvvmdi.R;
9 | import com.futurice.rxmvvmdi.RxMvvmApp;
10 | import com.futurice.rxmvvmdi.dagger.components.ActivityComponent;
11 | import com.futurice.rxmvvmdi.dagger.modules.ActivityModule;
12 | import com.futurice.rxmvvmdi.databinding.ActivityRxBindingExampleBinding;
13 | import com.futurice.rxmvvmdi.viewmodels.RxBindingExampleViewModel;
14 | import com.futurice.rxmvvmdi.viewmodels.ViewModel;
15 |
16 | import javax.inject.Inject;
17 |
18 | import rx.android.schedulers.AndroidSchedulers;
19 | import rx.schedulers.Schedulers;
20 | import rx.subscriptions.CompositeSubscription;
21 |
22 | /**
23 | * This activity introduces the following concepts:
24 | * - binding rx.Observables from the VM manually in the view layer to view components (without
25 | * declarative data-binding)
26 | * - using a base MvvmActivity to assist in controlling lifecycle events of the view and VM.
27 | * - the importance of understanding schedulers and their effect on Observable streams via
28 | * observerOn and subscribeOn. (Slightly modifying the streams in the view and VM will cause a
29 | * crash and/or main thread hangs when calling vm.calculate(), which can then be solved).
30 | */
31 | public class RxBindingExampleActivity extends MvvmActivity {
32 |
33 | private ActivityRxBindingExampleBinding binding;
34 |
35 | @Inject
36 | RxBindingExampleViewModel viewModel;
37 |
38 | @Override
39 | protected void onCreate(Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 |
42 | ActivityComponent component = RxMvvmApp.getAppComponent().plusActivity(new ActivityModule(this));
43 | component.inject(this);
44 |
45 | binding = DataBindingUtil.setContentView(this, R.layout.activity_rx_binding_example);
46 | binding.setHandlers(new Handlers());
47 | }
48 |
49 | @Override
50 | protected ViewModel getViewModel() {
51 | return viewModel;
52 | }
53 |
54 | @Override
55 | protected void bindView(CompositeSubscription subscriptions) {
56 | subscriptions.add(viewModel
57 | .getTimeStream()
58 | .observeOn(AndroidSchedulers.mainThread())
59 | .subscribe(time -> binding.timeText.setText(time)));
60 |
61 | subscriptions.add(viewModel
62 | .getHighLoadStream()
63 | .observeOn(AndroidSchedulers.mainThread())
64 | .subscribe(iteration -> binding.iterationsText.setText(iteration.toString())));
65 | }
66 |
67 | public class Handlers {
68 | public void onCalculate(View view) {
69 | viewModel.calculate();
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/activities/RxPropertyExampleActivity.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.activities;
2 |
3 | import android.databinding.DataBindingUtil;
4 | import android.os.Bundle;
5 |
6 | import com.futurice.rxmvvmdi.R;
7 | import com.futurice.rxmvvmdi.RxMvvmApp;
8 | import com.futurice.rxmvvmdi.dagger.modules.ActivityModule;
9 | import com.futurice.rxmvvmdi.databinding.ActivityRxPropertyExampleBinding;
10 | import com.futurice.rxmvvmdi.viewmodels.RxPropertyExampleViewModel;
11 | import com.futurice.rxmvvmdi.viewmodels.ViewModel;
12 |
13 | import javax.inject.Inject;
14 |
15 | /**
16 | * This activity is for demonstrating the use of RxProperties:
17 | * - binding RxProperties to rx.Observables
18 | * - binding RxProperties to the view using data-binding
19 | * - the VM also demonstrates the use of shared rx.Observables to avoid duplicate processing when
20 | * subscribing multiple times to the same source.
21 | */
22 | public class RxPropertyExampleActivity extends MvvmActivity {
23 |
24 | private ActivityRxPropertyExampleBinding binding;
25 |
26 | @Inject
27 | RxPropertyExampleViewModel viewModel;
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 |
33 | RxMvvmApp.getAppComponent()
34 | .plusActivity(new ActivityModule(this))
35 | .inject(this);
36 |
37 | binding = DataBindingUtil.setContentView(this, R.layout.activity_rx_property_example);
38 | binding.setVm(viewModel);
39 | }
40 |
41 | @Override
42 | protected ViewModel getViewModel() {
43 | return viewModel;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/activities/StaticBindingExampleActivity.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.activities;
2 |
3 | import android.databinding.BindingAdapter;
4 | import android.databinding.DataBindingUtil;
5 | import android.graphics.Color;
6 | import android.os.Bundle;
7 | import android.widget.TextView;
8 |
9 | import com.futurice.rxmvvmdi.R;
10 | import com.futurice.rxmvvmdi.RxMvvmApp;
11 | import com.futurice.rxmvvmdi.dagger.components.ActivityComponent;
12 | import com.futurice.rxmvvmdi.dagger.modules.ActivityModule;
13 | import com.futurice.rxmvvmdi.databinding.ActivityStaticBindingExampleBinding;
14 | import com.futurice.rxmvvmdi.viewmodels.StaticBindingExampleViewModel;
15 | import com.futurice.rxmvvmdi.viewmodels.ViewModel;
16 |
17 | import javax.inject.Inject;
18 |
19 | /**
20 | * This activity demonstrates static data-binding, introducing the following concepts:
21 | * - binding a VM and simple properties to the view using data-binding.
22 | * - VM property conversion to values suitable for displaying in the view using BindingAdapters.
23 | */
24 | public class StaticBindingExampleActivity extends MvvmActivity {
25 | @Inject
26 | StaticBindingExampleViewModel viewModel;
27 |
28 | private ActivityStaticBindingExampleBinding binding;
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 |
34 | ActivityComponent component = RxMvvmApp.getAppComponent().plusActivity(new ActivityModule(this));
35 | component.inject(this);
36 |
37 | binding = DataBindingUtil.setContentView(this, R.layout.activity_static_binding_example);
38 | binding.setVm(viewModel);
39 | }
40 |
41 | @Override
42 | protected ViewModel getViewModel() {
43 | return viewModel;
44 | }
45 |
46 | @BindingAdapter("android:textColor")
47 | public static void setTextColor(TextView view, StaticBindingExampleViewModel.CoffeeType coffeeType) {
48 | switch (coffeeType) {
49 | case CAPRICCIO:
50 | view.setTextColor(Color.argb(0xFF, 0x3E, 0xE4, 0x00));
51 | break;
52 | case LIVANTO:
53 | view.setTextColor(Color.argb(0xFF, 0xFF, 0x99, 0x00));
54 | break;
55 | default:
56 | view.setTextColor(Color.BLACK);
57 | break;
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/dagger/ActivityScope.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.dagger;
2 |
3 | import java.lang.annotation.Retention;
4 | import java.lang.annotation.RetentionPolicy;
5 |
6 | import javax.inject.Scope;
7 |
8 | @Scope
9 | @Retention(RetentionPolicy.RUNTIME)
10 | public @interface ActivityScope {
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/dagger/components/ActivityComponent.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.dagger.components;
2 |
3 | import android.app.Activity;
4 |
5 | import com.futurice.rxmvvmdi.activities.ListBindingExampleActivity;
6 | import com.futurice.rxmvvmdi.activities.MainActivity;
7 | import com.futurice.rxmvvmdi.activities.RxBindingExampleActivity;
8 | import com.futurice.rxmvvmdi.activities.RxPropertyExampleActivity;
9 | import com.futurice.rxmvvmdi.activities.StaticBindingExampleActivity;
10 | import com.futurice.rxmvvmdi.dagger.ActivityScope;
11 | import com.futurice.rxmvvmdi.dagger.modules.ActivityModule;
12 |
13 | import dagger.Subcomponent;
14 |
15 | @Subcomponent(modules = ActivityModule.class)
16 | @ActivityScope
17 | public interface ActivityComponent {
18 | Activity activity();
19 |
20 | void inject(MainActivity activity);
21 | void inject(StaticBindingExampleActivity activity);
22 | void inject(RxBindingExampleActivity activity);
23 | void inject(RxPropertyExampleActivity activity);
24 | void inject(ListBindingExampleActivity activity);
25 | }
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/dagger/components/AppComponent.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.dagger.components;
2 |
3 | import com.futurice.rxmvvmdi.RxMvvmApp;
4 | import com.futurice.rxmvvmdi.dagger.modules.ActivityModule;
5 | import com.futurice.rxmvvmdi.dagger.modules.AppModule;
6 |
7 | import javax.inject.Singleton;
8 |
9 | import dagger.Component;
10 |
11 | @Component(modules = AppModule.class)
12 | @Singleton
13 | public interface AppComponent {
14 |
15 | void inject(RxMvvmApp app);
16 |
17 | ActivityComponent plusActivity(ActivityModule activityModule);
18 |
19 | class Initializer {
20 | public static AppComponent init(final RxMvvmApp app) {
21 | return DaggerAppComponent.builder()
22 | .appModule(new AppModule(app))
23 | .build();
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/dagger/modules/ActivityModule.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.dagger.modules;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 |
6 | import com.futurice.rxmvvmdi.dagger.ActivityScope;
7 | import com.futurice.rxmvvmdi.services.NavigatorService;
8 | import com.futurice.rxmvvmdi.services.SystemMonitorService;
9 | import com.futurice.rxmvvmdi.viewmodels.MainViewModel;
10 | import com.futurice.rxmvvmdi.viewmodels.RxBindingExampleViewModel;
11 | import com.futurice.rxmvvmdi.viewmodels.RxPropertyExampleViewModel;
12 | import com.futurice.rxmvvmdi.viewmodels.StaticBindingExampleViewModel;
13 |
14 | import dagger.Module;
15 | import dagger.Provides;
16 |
17 | @Module
18 | public class ActivityModule {
19 | private final Activity activity;
20 |
21 | public ActivityModule(Activity activity) {
22 | this.activity = activity;
23 | }
24 |
25 | @Provides
26 | @ActivityScope
27 | Activity activity() {
28 | return this.activity;
29 | }
30 |
31 | @Provides
32 | @ActivityScope
33 | Context context() { return this.activity; }
34 |
35 | @Provides
36 | @ActivityScope
37 | NavigatorService provideNavigatorService(@ActivityScope Context context) {
38 | return new NavigatorService(context);
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/dagger/modules/AppModule.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.dagger.modules;
2 |
3 | import com.facebook.stetho.okhttp3.StethoInterceptor;
4 | import com.futurice.rxmvvmdi.RxMvvmApp;
5 | import com.futurice.rxmvvmdi.services.IBackendService;
6 | import com.futurice.rxmvvmdi.services.SystemMonitorService;
7 |
8 | import javax.inject.Singleton;
9 |
10 | import dagger.Module;
11 | import dagger.Provides;
12 | import okhttp3.OkHttpClient;
13 | import retrofit2.Retrofit;
14 | import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
15 | import retrofit2.converter.gson.GsonConverterFactory;
16 | import rx.schedulers.Schedulers;
17 |
18 | @Module
19 | public class AppModule {
20 | private final RxMvvmApp app;
21 |
22 | public AppModule(final RxMvvmApp app) {
23 | this.app = app;
24 | }
25 |
26 | @Provides
27 | @Singleton
28 | public RxMvvmApp provideApp() {
29 | return app;
30 | }
31 |
32 | @Provides
33 | @Singleton
34 | public SystemMonitorService provideSystemMonitorService() {
35 | return new SystemMonitorService();
36 | }
37 |
38 | @Provides
39 | @Singleton
40 | public IBackendService provideBackendService() {
41 | OkHttpClient httpClient = new OkHttpClient.Builder()
42 | .addNetworkInterceptor(new StethoInterceptor())
43 | .build();
44 |
45 | return new Retrofit.Builder()
46 | .client(httpClient)
47 | .baseUrl("http://jsonplaceholder.typicode.com")
48 | .addConverterFactory(GsonConverterFactory.create())
49 | .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
50 | .build()
51 | .create(IBackendService.class);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/models/Post.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.models;
2 |
3 | public class Post {
4 | private final int id;
5 | private final int userId;
6 | private final String title;
7 | private final String body;
8 |
9 | public Post(int id, int userId, String title, String body) {
10 | this.id = id;
11 | this.userId = userId;
12 | this.title = title;
13 | this.body = body;
14 | }
15 |
16 | public int getId() {
17 | return id;
18 | }
19 |
20 | public int getUserId() {
21 | return userId;
22 | }
23 |
24 | public String getTitle() {
25 | return title;
26 | }
27 |
28 | public String getBody() {
29 | return body;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/models/User.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.models;
2 |
3 | public class User {
4 | private final int id;
5 | private final String name;
6 |
7 | public User(int id, String name) {
8 | this.id = id;
9 | this.name = name;
10 | }
11 |
12 | public int getId() {
13 | return id;
14 | }
15 |
16 | public String getName() {
17 | return name;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/services/IBackendService.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.services;
2 |
3 | import com.futurice.rxmvvmdi.models.Post;
4 | import com.futurice.rxmvvmdi.models.User;
5 |
6 | import java.util.List;
7 |
8 | import retrofit2.http.GET;
9 | import retrofit2.http.Path;
10 | import rx.Observable;
11 |
12 | public interface IBackendService {
13 | @GET("posts")
14 | Observable> getPosts();
15 |
16 | @GET("users/{userId}")
17 | Observable getUser(@Path("userId") int userId);
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/services/NavigatorService.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.services;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.Intent;
6 | import android.support.annotation.NonNull;
7 |
8 | import com.futurice.rxmvvmdi.dagger.ActivityScope;
9 |
10 | public class NavigatorService {
11 |
12 | private final Context context;
13 |
14 | public NavigatorService(@NonNull final Context context) {
15 | this.context = context;
16 | }
17 |
18 | public void goTo(Class activity) {
19 | context.startActivity(new Intent(context, activity));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/services/SystemMonitorService.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.services;
2 |
3 | import android.util.Log;
4 |
5 | import java.io.BufferedReader;
6 | import java.io.IOException;
7 | import java.io.InputStreamReader;
8 | import java.util.ArrayList;
9 | import java.util.List;
10 | import java.util.concurrent.TimeUnit;
11 | import java.util.regex.Pattern;
12 |
13 | import rx.Observable;
14 | import rx.functions.Func1;
15 |
16 | /**
17 | * Created by osal on 3.5.2016.
18 | */
19 | public class SystemMonitorService {
20 |
21 | public Observable getCpuUtilizationStream() {
22 | final Pattern pattern = Pattern.compile("\\d+");
23 | return Observable
24 | .interval(1000, TimeUnit.MILLISECONDS)
25 | .map(t -> executeTop())
26 | .filter(topOutput -> topOutput != null && topOutput.length() > 0)
27 | .map(topOutput -> pattern.matcher(topOutput))
28 | .flatMap(matcher -> {
29 | List values = new ArrayList();
30 | while (matcher.find()) {
31 | values.add(Float.parseFloat(matcher.group()));
32 | }
33 | return Observable
34 | .from(values)
35 | .take(2)
36 | .reduce(0F, (sum, next) -> sum + next);
37 | });
38 | }
39 |
40 | private static String executeTop() {
41 | java.lang.Process p = null;
42 | BufferedReader in = null;
43 | String returnString = null;
44 | try {
45 | p = Runtime.getRuntime().exec("top -n 1");
46 | in = new BufferedReader(new InputStreamReader(p.getInputStream()));
47 | while (returnString == null || returnString.contentEquals("")) {
48 | returnString = in.readLine();
49 | }
50 | } catch (IOException e) {
51 | Log.e("executeTop", "error in getting first line of top");
52 | e.printStackTrace();
53 | } finally {
54 | try {
55 | in.close();
56 | p.destroy();
57 | } catch (IOException e) {
58 | Log.e("executeTop",
59 | "error in closing and destroying top process");
60 | e.printStackTrace();
61 | }
62 | }
63 | Log.d("CPU", returnString);
64 | return returnString;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/viewmodels/ListBindingExampleViewModel.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import android.databinding.ObservableArrayList;
4 | import android.databinding.ObservableList;
5 | import android.support.annotation.NonNull;
6 |
7 | import com.futurice.rxmvvmdi.models.Post;
8 | import com.futurice.rxmvvmdi.services.IBackendService;
9 |
10 | import java.util.concurrent.TimeUnit;
11 |
12 | import javax.inject.Inject;
13 |
14 | import rx.Observable;
15 | import rx.android.schedulers.AndroidSchedulers;
16 | import rx.subscriptions.CompositeSubscription;
17 |
18 | /**
19 | * Created by osal on 16.5.2016.
20 | */
21 | public class ListBindingExampleViewModel extends ViewModel {
22 |
23 | public final ObservableList posts;
24 |
25 | private final IBackendService backendService;
26 |
27 | @Inject
28 | public ListBindingExampleViewModel(@NonNull final IBackendService backendService) {
29 | this.backendService = backendService;
30 | posts = new ObservableArrayList<>();
31 | }
32 |
33 | @Override
34 | protected void subscribe(@NonNull CompositeSubscription subscriptions) {
35 | // Demonstrates the dynamic nature of the collection data binding by adding new items
36 | // to the list every itemAddDelayMs.
37 | final long itemAddDelayMs = 200;
38 | subscriptions.add(backendService
39 | .getPosts()
40 | .flatMap(posts -> {
41 | return Observable.from(posts)
42 | .startWith((Post)null)
43 | .zipWith(Observable.interval(itemAddDelayMs, TimeUnit.MILLISECONDS), (post, time) -> post);
44 | })
45 | .observeOn(AndroidSchedulers.mainThread())
46 | .subscribe(post -> {
47 | if (post == null) {
48 | posts.clear();
49 | }
50 | else {
51 | posts.add(post);
52 | }
53 | })
54 | );
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/viewmodels/MainViewModel.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import com.futurice.rxmvvmdi.activities.ListBindingExampleActivity;
6 | import com.futurice.rxmvvmdi.activities.RxBindingExampleActivity;
7 | import com.futurice.rxmvvmdi.activities.RxPropertyExampleActivity;
8 | import com.futurice.rxmvvmdi.activities.StaticBindingExampleActivity;
9 | import com.futurice.rxmvvmdi.services.NavigatorService;
10 |
11 | import javax.inject.Inject;
12 |
13 | import rx.subscriptions.CompositeSubscription;
14 |
15 | public class MainViewModel extends ViewModel {
16 |
17 | private final NavigatorService navigatorService;
18 |
19 | @Inject
20 | public MainViewModel(@NonNull final NavigatorService navigatorService) {
21 | this.navigatorService = navigatorService;
22 | }
23 |
24 | @Override
25 | protected void subscribe(@NonNull CompositeSubscription subscriptions) {
26 | }
27 |
28 | public void selectStaticDataBinding() {
29 | navigatorService.goTo(StaticBindingExampleActivity.class);
30 | }
31 |
32 | public void selectRxBinding() {
33 | navigatorService.goTo(RxBindingExampleActivity.class);
34 | }
35 |
36 | public void selectRxProperty() {
37 | navigatorService.goTo(RxPropertyExampleActivity.class);
38 | }
39 |
40 | public void selectListBinding() {
41 | navigatorService.goTo(ListBindingExampleActivity.class);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/viewmodels/RxBindingExampleViewModel.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import org.threeten.bp.Duration;
6 | import org.threeten.bp.LocalTime;
7 | import org.threeten.bp.format.DateTimeFormatter;
8 |
9 | import java.util.concurrent.TimeUnit;
10 |
11 | import javax.inject.Inject;
12 |
13 | import rx.Observable;
14 | import rx.schedulers.Schedulers;
15 | import rx.subjects.PublishSubject;
16 | import rx.subscriptions.CompositeSubscription;
17 |
18 | public class RxBindingExampleViewModel extends ViewModel {
19 |
20 | private final Observable timeStream;
21 | private final Observable highLoadStream;
22 | private final PublishSubject calculateSubject;
23 |
24 | @Inject
25 | public RxBindingExampleViewModel() {
26 | final long intervalMs = 10;
27 | final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("mm:ss:SS");
28 |
29 | timeStream = Observable
30 | .interval(intervalMs, TimeUnit.MILLISECONDS)
31 | .onBackpressureDrop()
32 | .map(beats -> Duration.ofMillis(intervalMs * beats))
33 | .map(duration -> formatter.format(LocalTime.MIDNIGHT.plus(duration)));
34 |
35 | calculateSubject = PublishSubject.create();
36 | highLoadStream = calculateSubject
37 | .observeOn(Schedulers.computation())
38 | .scan((sum, value) -> ++sum)
39 | .map(iteration -> {
40 | // Simulate high processing load
41 | try {
42 | Thread.sleep(1000);
43 | }
44 | catch (InterruptedException e) {}
45 | return iteration;
46 | });
47 | }
48 |
49 | @Override
50 | protected void subscribe(@NonNull CompositeSubscription subscriptions) {
51 | }
52 |
53 | public void calculate() {
54 | calculateSubject.onNext(1);
55 | }
56 |
57 | public Observable getTimeStream() {
58 | return timeStream;
59 | }
60 |
61 | public Observable getHighLoadStream() {
62 | return highLoadStream;
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/viewmodels/RxProperty.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import android.databinding.BindingAdapter;
4 | import android.databinding.ObservableField;
5 | import android.support.annotation.NonNull;
6 | import android.text.Editable;
7 | import android.text.TextWatcher;
8 | import android.util.Log;
9 | import android.widget.EditText;
10 |
11 | import rx.android.schedulers.AndroidSchedulers;
12 | import rx.functions.Action1;
13 | import rx.subjects.PublishSubject;
14 | import rx.subjects.SerializedSubject;
15 |
16 | /**
17 | * RxProperty based on the https://github.com/k-kagurazaka/rx-property-android ReactiveProperty port.
18 | * The main differences between this and the original are that this class:
19 | * - can be bound and unbound multiple times
20 | * - can be directly set as an observer in an Rx subscription
21 | * - supports chaining by exposing the internal Rx value stream
22 | * - automatically observes on the main thread
23 | */
24 | public class RxProperty implements rx.Observer {
25 |
26 | private static final String TAG = RxProperty.class.getName();
27 |
28 | private final SerializedSubject subject = new SerializedSubject(PublishSubject.create());
29 | private final rx.Observable output;
30 | private final ObservableField value;
31 |
32 | public RxProperty() {
33 | value = new ObservableField<>();
34 | output = subject.asObservable();
35 | init();
36 | }
37 |
38 | public RxProperty(final T startValue) {
39 | value = new ObservableField<>();
40 | output = subject.startWith(startValue);
41 | init();
42 | }
43 |
44 | public T getValue() {
45 | return value.get();
46 | }
47 |
48 | public void setValue(T t) {
49 | onNext(t);
50 | }
51 |
52 | @NonNull
53 | public rx.Observable getStream() {
54 | return output;
55 | }
56 |
57 | @Override
58 | public void onCompleted() {
59 | subject.onCompleted();
60 | }
61 |
62 | @Override
63 | public void onError(Throwable e) {
64 | subject.onError(e);
65 | }
66 |
67 | @Override
68 | public void onNext(T t) {
69 | subject.onNext(t);
70 | }
71 |
72 | private void init() {
73 | // The property is expected to be bound to UI elements, so we assume that consumers
74 | // no not care about the full history of value changes. Therefore, we apply backpressure
75 | // handling by taking the latest value and ignore duplicate values.
76 | output.onBackpressureLatest()
77 | .distinctUntilChanged()
78 | .observeOn(AndroidSchedulers.mainThread())
79 | .subscribe(new Action1() {
80 | @Override
81 | public void call(T t) {
82 | value.set(t);
83 | }
84 | }, new Action1() {
85 | @Override
86 | public void call(Throwable throwable) {
87 | Log.e(TAG, "onError: " + throwable.getMessage());
88 | throwable.printStackTrace();
89 | }
90 | });
91 | }
92 |
93 | /**
94 | * Data-binding related methods. The getGet, getSet, setGet, setSet methods are for allowing
95 | * the data-binding library to access either the ObservableField or the RxProperty itself
96 | * depending on whether the property is used for reading or writing.
97 | */
98 | @Deprecated
99 | public ObservableField getGet() {
100 | return value;
101 | }
102 |
103 | @Deprecated
104 | public void setGet() {
105 | }
106 |
107 | @Deprecated
108 | public RxProperty getSet() {
109 | return this;
110 | }
111 |
112 | @Deprecated
113 | public void setSet(RxProperty property) {
114 | }
115 |
116 | @BindingAdapter("bindset")
117 | public static void bindEditText(EditText editText, RxProperty property) {
118 | editText.addTextChangedListener(new TextWatcher() {
119 | @Override
120 | public void beforeTextChanged(CharSequence s, int start, int count, int after) {
121 |
122 | }
123 |
124 | @Override
125 | public void onTextChanged(CharSequence s, int start, int before, int count) {
126 |
127 | }
128 |
129 | @Override
130 | public void afterTextChanged(Editable s) {
131 | property.setValue(s.toString());
132 | }
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/viewmodels/RxPropertyExampleViewModel.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import com.futurice.rxmvvmdi.services.SystemMonitorService;
6 |
7 | import javax.inject.Inject;
8 |
9 | import rx.Observable;
10 | import rx.subscriptions.CompositeSubscription;
11 |
12 | public class RxPropertyExampleViewModel extends ViewModel {
13 |
14 | public final RxProperty cpuUsage;
15 | public final RxProperty maxCpuUsage;
16 | public final RxProperty customInput;
17 | public final RxProperty upperCaseInput;
18 |
19 | private final SystemMonitorService systemMonitorService;
20 |
21 | @Inject
22 | public RxPropertyExampleViewModel(@NonNull final SystemMonitorService systemMonitorService) {
23 | this.systemMonitorService = systemMonitorService;
24 | cpuUsage = new RxProperty<>();
25 | maxCpuUsage = new RxProperty<>();
26 | customInput = new RxProperty<>();
27 | upperCaseInput = new RxProperty<>();
28 | }
29 |
30 | @Override
31 | protected void subscribe(@NonNull CompositeSubscription subscriptions) {
32 | Observable cpuUtzStream = systemMonitorService
33 | .getCpuUtilizationStream()
34 | .share();
35 | subscriptions.add(cpuUtzStream
36 | .map(usage -> usage + "%")
37 | .subscribe(cpuUsage)
38 | );
39 | subscriptions.add(cpuUtzStream
40 | .scan((max, value) -> Math.max(max, value))
41 | .map(usage -> usage + "%")
42 | .subscribe(maxCpuUsage)
43 | );
44 | subscriptions.add(customInput
45 | .getStream()
46 | .filter(input -> input != null)
47 | .map(input -> input.toUpperCase())
48 | .subscribe(upperCaseInput));
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/viewmodels/StaticBindingExampleViewModel.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import javax.inject.Inject;
6 |
7 | import rx.subscriptions.CompositeSubscription;
8 |
9 | public class StaticBindingExampleViewModel extends ViewModel {
10 |
11 | public enum CoffeeType {
12 | CAPRICCIO,
13 | LIVANTO
14 | }
15 |
16 | public Capsule capsule;
17 |
18 | @Inject
19 | public StaticBindingExampleViewModel() {
20 | capsule = new Capsule(CoffeeType.LIVANTO, "Livanto");
21 | }
22 |
23 | @Override
24 | protected void subscribe(@NonNull CompositeSubscription subscriptions) {
25 | }
26 |
27 | public class Capsule {
28 | public final CoffeeType type;
29 | public final String name;
30 |
31 | public Capsule(final CoffeeType type, @NonNull final String name) {
32 | this.type = type;
33 | this.name = name;
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/app/src/main/java/com/futurice/rxmvvmdi/viewmodels/ViewModel.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import android.support.annotation.NonNull;
4 |
5 | import rx.subscriptions.CompositeSubscription;
6 |
7 | /**
8 | * Base VM class that can be used by activities and fragments to manage VM lifecycles in a
9 | * consistent manner.
10 | */
11 | public abstract class ViewModel {
12 |
13 | private final CompositeSubscription subscriptions;
14 |
15 | public ViewModel() {
16 | subscriptions = new CompositeSubscription();
17 | }
18 |
19 | public void bind() {
20 | subscriptions.clear();
21 | CompositeSubscription newSubscriptions = new CompositeSubscription();
22 | subscribe(newSubscriptions);
23 | subscriptions.add(newSubscriptions);
24 | }
25 |
26 | public void unbind() {
27 | subscriptions.clear();
28 | }
29 |
30 | protected abstract void subscribe(@NonNull final CompositeSubscription subscriptions);
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_list_binding_example.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
13 |
14 |
15 |
25 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
13 |
14 |
15 |
25 |
26 |
31 |
32 |
37 |
38 |
43 |
44 |
49 |
50 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_rx_binding_example.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
10 |
11 |
12 |
21 |
22 |
27 |
28 |
35 |
36 |
44 |
45 |
52 |
53 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_rx_property_example.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
10 |
11 |
12 |
21 |
22 |
27 |
28 |
35 |
36 |
42 |
43 |
50 |
51 |
57 |
58 |
65 |
66 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_static_binding_example.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
10 |
11 |
20 |
21 |
28 |
29 |
36 |
37 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/item_post.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
10 |
11 |
15 |
21 |
22 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/futurice/android-rxmvvmdi/a633ae18e56003a6f0fc04f591b33973f38452cb/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/futurice/android-rxmvvmdi/a633ae18e56003a6f0fc04f591b33973f38452cb/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/futurice/android-rxmvvmdi/a633ae18e56003a6f0fc04f591b33973f38452cb/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/futurice/android-rxmvvmdi/a633ae18e56003a6f0fc04f591b33973f38452cb/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/futurice/android-rxmvvmdi/a633ae18e56003a6f0fc04f591b33973f38452cb/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 | #000000
7 | #FF0000
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | RxMvvmDi
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/futurice/rxmvvmdi/DelegatingTestScheduler.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi;
2 |
3 | import rx.Scheduler;
4 | import rx.schedulers.TestScheduler;
5 |
6 | // Possible solution to RxJava caching schedulers
7 | // https://github.com/ReactiveX/RxJava/issues/3914
8 | public class DelegatingTestScheduler extends Scheduler {
9 |
10 | private TestScheduler innerScheduler;
11 |
12 | @Override
13 | public Worker createWorker() {
14 | return innerScheduler.createWorker();
15 | }
16 |
17 | @Override
18 | public long now() {
19 | return innerScheduler.now();
20 | }
21 |
22 | TestScheduler getInnerScheduler() {
23 | return innerScheduler;
24 | }
25 |
26 | void setInnerScheduler(TestScheduler innerScheduler) {
27 | this.innerScheduler = innerScheduler;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/app/src/test/java/com/futurice/rxmvvmdi/RxTest.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi;
2 |
3 | import org.junit.Before;
4 | import org.junit.BeforeClass;
5 | import org.mockito.MockitoAnnotations;
6 |
7 | import rx.Scheduler;
8 | import rx.android.plugins.RxAndroidPlugins;
9 | import rx.android.plugins.RxAndroidSchedulersHook;
10 | import rx.plugins.RxJavaPlugins;
11 | import rx.plugins.RxJavaSchedulersHook;
12 | import rx.schedulers.TestScheduler;
13 |
14 | /**
15 | * Base class for tests that initializes all mocks annotated with @Mock using Mockito.
16 | * It also sets up TestSchedulers for all Rx schedulers so Rx streams can be tested more reliably
17 | * regardless of which thread they run on normally.
18 | */
19 | public abstract class RxTest {
20 |
21 | private static final DelegatingTestScheduler delegatingMainScheduler = new DelegatingTestScheduler();
22 | private static final DelegatingTestScheduler delegatingIoScheduler = new DelegatingTestScheduler();
23 | private static final DelegatingTestScheduler delegatingComputationScheduler = new DelegatingTestScheduler();
24 | private static final DelegatingTestScheduler delegatingNewThreadScheduler = new DelegatingTestScheduler();
25 |
26 | @BeforeClass
27 | public static void initSchedulers() {
28 | RxJavaPlugins.getInstance().reset();
29 | RxJavaPlugins.getInstance().registerSchedulersHook(new RxJavaSchedulersHook() {
30 | @Override
31 | public Scheduler getComputationScheduler() {
32 | return delegatingComputationScheduler;
33 | }
34 |
35 | @Override
36 | public Scheduler getIOScheduler() {
37 | return delegatingIoScheduler;
38 | }
39 |
40 | @Override
41 | public Scheduler getNewThreadScheduler() {
42 | return delegatingNewThreadScheduler;
43 | }
44 | });
45 |
46 | RxAndroidPlugins.getInstance().reset();
47 | RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() {
48 | @Override
49 | public Scheduler getMainThreadScheduler() {
50 | return delegatingMainScheduler;
51 | }
52 | });
53 | }
54 |
55 | @Before
56 | public void init() {
57 | resetSchedulers();
58 | MockitoAnnotations.initMocks(this);
59 | setup();
60 | }
61 |
62 | private void resetSchedulers() {
63 | delegatingMainScheduler.setInnerScheduler(new TestScheduler());
64 | delegatingIoScheduler.setInnerScheduler(new TestScheduler());
65 | delegatingComputationScheduler.setInnerScheduler(new TestScheduler());
66 | delegatingNewThreadScheduler.setInnerScheduler(new TestScheduler());
67 | }
68 |
69 | protected abstract void setup();
70 |
71 | protected TestScheduler mainScheduler() {
72 | return delegatingMainScheduler.getInnerScheduler();
73 | }
74 |
75 | protected TestScheduler ioScheduler() {
76 | return delegatingIoScheduler.getInnerScheduler();
77 | }
78 |
79 | protected TestScheduler computationScheduler() {
80 | return delegatingComputationScheduler.getInnerScheduler();
81 | }
82 |
83 | protected TestScheduler newThreadScheduler() {
84 | return delegatingNewThreadScheduler.getInnerScheduler();
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/app/src/test/java/com/futurice/rxmvvmdi/viewmodels/MainActivityViewModelTest.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import android.test.suitebuilder.annotation.SmallTest;
4 |
5 | import com.futurice.rxmvvmdi.RxTest;
6 | import com.futurice.rxmvvmdi.activities.StaticBindingExampleActivity;
7 | import com.futurice.rxmvvmdi.services.NavigatorService;
8 |
9 | import org.junit.Test;
10 | import org.mockito.Mock;
11 |
12 | import static org.mockito.Mockito.verify;
13 |
14 | @SmallTest
15 | public class MainActivityViewModelTest extends RxTest {
16 |
17 | @Mock
18 | private NavigatorService navigator;
19 |
20 | private MainViewModel viewModel;
21 |
22 | protected void setup() {
23 | viewModel = new MainViewModel(navigator);
24 | }
25 |
26 | @Test
27 | public void selectStaticDataBinding_navigatesToStaticBindingExample() {
28 | viewModel.selectStaticDataBinding();
29 | verify(navigator).goTo(StaticBindingExampleActivity.class);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/test/java/com/futurice/rxmvvmdi/viewmodels/RxBindingExampleViewModelTest.java:
--------------------------------------------------------------------------------
1 | package com.futurice.rxmvvmdi.viewmodels;
2 |
3 | import com.futurice.rxmvvmdi.RxTest;
4 |
5 | import org.junit.Test;
6 |
7 | import java.util.concurrent.TimeUnit;
8 |
9 | import rx.observers.TestSubscriber;
10 |
11 | public class RxBindingExampleViewModelTest extends RxTest {
12 |
13 | private RxBindingExampleViewModel viewModel;
14 |
15 | protected void setup() {
16 | viewModel = new RxBindingExampleViewModel();
17 | }
18 |
19 | @Test
20 | public void timeStream_incrementsEveryTenMilliseconds() {
21 | TestSubscriber subscriber = new TestSubscriber();
22 | viewModel.getTimeStream().subscribe(subscriber);
23 | computationScheduler().advanceTimeBy(20, TimeUnit.MILLISECONDS);
24 | subscriber.assertValues("00:00:00", "00:00:01");
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.0.0'
9 |
10 | // Assists in working with annotation processors for Android Studio (for Dagger2)
11 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
12 |
13 | // Retrolambda
14 | classpath 'me.tatarka:gradle-retrolambda:3.2.5'
15 | }
16 | }
17 |
18 | allprojects {
19 | repositories {
20 | jcenter()
21 | }
22 | }
23 |
24 | task clean(type: Delete) {
25 | delete rootProject.buildDir
26 | }
27 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/futurice/android-rxmvvmdi/a633ae18e56003a6f0fc04f591b33973f38452cb/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 28 10:00:20 PST 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/set-branch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/futurice/android-rxmvvmdi/a633ae18e56003a6f0fc04f591b33973f38452cb/set-branch.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------