data = new ArrayList<>();
47 |
48 |
49 | // preparing navigation drawer items
50 | for (int i = 0; i < titles.length; i++) {
51 | NavDrawerItem navItem = new NavDrawerItem();
52 | navItem.setTitle(titles[i]);
53 | data.add(navItem);
54 | }
55 | return data;
56 | }
57 |
58 | @Override
59 | public void onCreate(Bundle savedInstanceState) {
60 | super.onCreate(savedInstanceState);
61 |
62 | // drawer labels
63 | titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
64 | }
65 |
66 | @Override
67 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
68 | Bundle savedInstanceState) {
69 | // Inflating view layout
70 | View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
71 | recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
72 |
73 | adapter = new NavigationDrawerAdapter(getActivity(), getData());
74 | recyclerView.setAdapter(adapter);
75 | recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
76 | recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
77 | @Override
78 | public void onClick(View view, int position) {
79 | drawerListener.onDrawerItemSelected(view, position);
80 | mDrawerLayout.closeDrawer(containerView);
81 | }
82 |
83 | @Override
84 | public void onLongClick(View view, int position) {
85 |
86 | }
87 | }));
88 |
89 | return layout;
90 | }
91 |
92 |
93 | public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
94 | containerView = getActivity().findViewById(fragmentId);
95 | mDrawerLayout = drawerLayout;
96 | mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
97 | @Override
98 | public void onDrawerOpened(View drawerView) {
99 | super.onDrawerOpened(drawerView);
100 | getActivity().invalidateOptionsMenu();
101 | }
102 |
103 | @Override
104 | public void onDrawerClosed(View drawerView) {
105 | super.onDrawerClosed(drawerView);
106 | getActivity().invalidateOptionsMenu();
107 | }
108 |
109 | @Override
110 | public void onDrawerSlide(View drawerView, float slideOffset) {
111 | super.onDrawerSlide(drawerView, slideOffset);
112 | toolbar.setAlpha(1 - slideOffset / 2);
113 | }
114 | };
115 |
116 | mDrawerLayout.setDrawerListener(mDrawerToggle);
117 | mDrawerLayout.post(new Runnable() {
118 | @Override
119 | public void run() {
120 | mDrawerToggle.syncState();
121 | }
122 | });
123 |
124 | }
125 |
126 | public static interface ClickListener {
127 | public void onClick(View view, int position);
128 |
129 | public void onLongClick(View view, int position);
130 | }
131 |
132 | static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
133 |
134 | private GestureDetector gestureDetector;
135 | private ClickListener clickListener;
136 |
137 | public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
138 | this.clickListener = clickListener;
139 | gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
140 | @Override
141 | public boolean onSingleTapUp(MotionEvent e) {
142 | return true;
143 | }
144 |
145 | @Override
146 | public void onLongPress(MotionEvent e) {
147 | View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
148 | if (child != null && clickListener != null) {
149 | clickListener.onLongClick(child, recyclerView.getChildPosition(child));
150 | }
151 | }
152 | });
153 | }
154 |
155 | @Override
156 | public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
157 |
158 | View child = rv.findChildViewUnder(e.getX(), e.getY());
159 | if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
160 | clickListener.onClick(child, rv.getChildPosition(child));
161 | }
162 | return false;
163 | }
164 |
165 | @Override
166 | public void onTouchEvent(RecyclerView rv, MotionEvent e) {
167 | }
168 |
169 | @Override
170 | public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
171 |
172 | }
173 |
174 |
175 | }
176 |
177 | public interface FragmentDrawerListener {
178 | public void onDrawerItemSelected(View view, int position);
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | [](https://android-arsenal.com/details/3/3998)
5 | # SimpleDroidRx
6 | An application that helps you learn and understand better ReactiveX on Android.
7 |
8 | ### Introduction
9 | I've created this project because, as everyone knows, learn ReactiveX from scratch is a tremendous challenge, and it has a pretty steep learning curve. So I tried to bring together all the samples I found useful to appreciate ReactiveX and how to use it on an Android app.
10 | ### How does it works ?
11 | With SimpleDroidRx app, you have several fragments. Each one contains some examples of ReactiveX. Each example is performed using those Rx libraries :
12 | * [RxJava] : RxJava is a Java VM implementation of Reactive Extensions: a library for composing asynchronous and event-based programs by using observable sequences.
13 | * [RxAndroid] : Android specific bindings for RxJava.
14 | * [RxBroadcast] : Reactive Broadcast and LocalBroadcast for Android.
15 | * [RxBinding] : RxJava binding APIs for Android UI widgets from the platform and support libraries.
16 |
17 | It also uses these massive libraries:
18 | * [ButterKnife] : Bind Android views and callbacks to fields and methods.
19 | * [Retrofit] :A type-safe HTTP client for Android and Java
20 | * [Dagger2] : Dagger is a fully static, compile-time dependency injection framework for both Java and Android. It is an adaptation of an earlier version created by Square and now maintained by Google.
21 |
22 | ### Mini Screenshots
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 | ### Demo
33 | You can test this app with appetize: https://appetize.io/app/g57uqpd3m4nn8w45v0r8awfq9w
34 |
35 | ### List of Samples
36 | Each sample is on a fragment and set up in the navigation drawer. It's sorted by level of complexity (from top to bottom). Also, on each sample, an explanatory TextView is here to briefly explain what's happening:
37 | * [Hello World] : In this fragment, you'll learn how to use an Observable and Observer. Also, you'll create your first stream and use your first operator : map( ).
38 |
39 | >Explanation: When you click on the button "Map( ) my words", you'll subscribe to an observable on TextView Text. The relative stream (myStream) replaces the words "Massive View Controller" by "MVVM", "Hell Callback" by "ReactiveX" and "AsyncTask" by "RxJava". Finally it adds at the end of TextView "<3 <3 <3".
40 |
41 | * [Famous Operator] : In this fragment, you'll learn the most commons operators and will get used to them : flatMap( ), filter( ), take( ), doOnNext( )
42 |
43 | >Explanation: When you click on "Play Happy !" or use the SeekBar, you'll subscribe to an observable on a string array. The relative stream (myStream) observes each item of string array, and apply to it some functions (setSmileyToItem, setCarriotReturnToItem & filterVersionAndroidThatSucks). It also takes only the number of item set by take( ).Finally, each item is shown in the TextView.
44 |
45 | * [Error Handling] : In this fragment, you'll learn how to handle error properly. You'll use map( ) and onError ().
46 |
47 | >Explanation: When you press button, you'll subscribe to an observable to relative TextView text. The relative stream (myStreamThatHandleError) executes a function that will test String. If it contains "callback" AND "hell" then it will throw an error.
48 |
49 | * [Background Tasks] : In this fragment, you'll learn how to run one and multiple tasks in the background.
50 |
51 | >Explanation: When you press the simple "SIMPLE TASK" button, you'll subscribe to an observable that execute a single task running in background (During 4sec) and stop.
52 | When you press the "DOUBLE TASKS" button, you'll subscribe to another one observable that executes a first long task to the background (During 8sec) and when over, a second single task will start (During 4 sec).
53 |
54 | * [Android Simple Sample] : In this fragment, you'll learn how to set an observer to a button using RxView.clicks( ), and intercept network changes.
55 |
56 | >Explanation: When you start fragment, you subscribe to an observable on a network changes. When you disable Wifi or mobile connection, you'll get notified by a Snackbar.
57 | When you press the "SHOW" button, it subscribes to an observable. It will show a Snackbar.
58 |
59 | * [Android REST Sample With Dagger2] : In this fragment, you'll learn how to make multiple http requests with only single stream. Also, you will learn how to use RxJava with Dagger2 injection.
60 |
61 | >Explanation: When you press "REFRESH" button, it will subscribe to an observable that gets Github followers of each person you've defined (In a String array), and after processing of requests, update the TextView.
62 |
63 | ### Contribute
64 | It will be awesome if you contribute to this project adding your own sample(s). Just follow this checklist :
65 |
66 | - 1 Create a Fragment and name it with the name of your sample. Put it on "Fragments" package. Also, create it's layout. You could use the other fragment as a model.
67 |
68 |
69 |
70 | - 2 Add your fragment in MainActivity on "displayView" function.
71 |
72 |
73 |
74 | - 3 Add the title of your sample in string.xml on related array (nav_drawer_labels)
75 |
76 |
77 |
78 | - 4 You can also modify the icon menu of your sample in NavigationDrawerAdapter on "getRessource" function.
79 |
80 |
81 |
82 | - 5 Update this README.md with your own infos.
83 | - 6 Make a pull request !
84 |
85 | License
86 | -------
87 |
88 | Copyright (C) 2016 Philippe Boisney
89 |
90 | Licensed under the Apache License, Version 2.0 (the "License");
91 | you may not use this file except in compliance with the License.
92 | You may obtain a copy of the License at
93 |
94 | http://www.apache.org/licenses/LICENSE-2.0
95 |
96 | Unless required by applicable law or agreed to in writing, software
97 | distributed under the License is distributed on an "AS IS" BASIS,
98 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
99 | See the License for the specific language governing permissions and
100 | limitations under the License.
101 |
102 | [RxJava]:
103 | [RxAndroid]:
104 | [ButterKnife]:
105 | [Retrofit]:
106 | [RxBroadcast]:
107 | [RxBinding]:
108 | [Dagger2]:
109 |
110 | [Hello World]:
111 | [Famous Operator]:
112 | [Error Handling]:
113 | [Background Tasks]:
114 | [Android Simple Sample]:
115 | [Android REST Sample With Dagger2]:
116 |
--------------------------------------------------------------------------------
/app/src/main/java/com/cookminute/simpledroidrx/UI/Fragments/Background_Tasks_Fragment.java:
--------------------------------------------------------------------------------
1 | package com.cookminute.simpledroidrx.UI.Fragments;
2 |
3 | import android.os.Bundle;
4 | import android.support.percent.PercentRelativeLayout;
5 | import android.support.v4.app.Fragment;
6 | import android.text.method.ScrollingMovementMethod;
7 | import android.util.Log;
8 | import android.view.LayoutInflater;
9 | import android.view.View;
10 | import android.view.ViewGroup;
11 | import android.widget.TextView;
12 |
13 | import com.cookminute.simpledroidrx.R;
14 | import com.cookminute.simpledroidrx.Utils.Commons.Functions;
15 |
16 | import butterknife.BindView;
17 | import butterknife.ButterKnife;
18 | import butterknife.OnClick;
19 | import butterknife.Unbinder;
20 | import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
21 | import rx.Observable;
22 | import rx.Observer;
23 | import rx.Subscriber;
24 | import rx.Subscription;
25 | import rx.android.schedulers.AndroidSchedulers;
26 | import rx.schedulers.Schedulers;
27 | import rx.subjects.BehaviorSubject;
28 |
29 | /**
30 | * Created by Philippe on 20/07/16.
31 | */
32 | public class Background_Tasks_Fragment extends Fragment {
33 |
34 | @BindView(R.id.root_view) PercentRelativeLayout rootView;
35 | @BindView(R.id.progressNormal) SmoothProgressBar progressNormal;
36 | @BindView(R.id.progressLong) SmoothProgressBar progressLong;
37 | @BindView(R.id.txtView) TextView title;
38 | @BindView(R.id.txtViewCounter) TextView txtViewCounter;
39 | @BindView(R.id.txtStateLong) TextView txtViewStateLong;
40 | @BindView(R.id.txtStateNormal) TextView txtViewStateNormal;
41 | @BindView(R.id.txtViewHelp) TextView txtViewHelp;
42 |
43 | private Unbinder unbinder;
44 |
45 | private Subscription subscription;
46 |
47 | private BehaviorSubject counterRunningTasks = BehaviorSubject.create(0);
48 | private int counterLongRunningTask = 0;
49 | private int counterNormalRunningTask = 0;
50 |
51 | public Background_Tasks_Fragment() { }
52 |
53 | @Override
54 | public void onCreate(Bundle savedInstanceState) {
55 | super.onCreate(savedInstanceState);
56 |
57 | //Subscribe our counter of tasks to its observer
58 | subscription = counterRunningTasks
59 | .subscribeOn(Schedulers.io())
60 | .observeOn(AndroidSchedulers.mainThread())
61 | .subscribe(getObserverCounter());
62 | }
63 |
64 | @Override
65 | public void onDestroy() {
66 | super.onDestroy();
67 | unbinder.unbind();
68 | }
69 |
70 | @Override
71 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
72 | View rootView = inflater.inflate(R.layout.fragment_background_tasks, container, false);
73 | unbinder = ButterKnife.bind(this, rootView);
74 | txtViewHelp.setMovementMethod(new ScrollingMovementMethod());
75 | return rootView;
76 | }
77 |
78 |
79 | // -------------------------------------------------------------
80 | // ACTIONS
81 | // -------------------------------------------------------------
82 |
83 | @OnClick(R.id.btn_start1)
84 | public void onClickStart1(final View v){
85 | this.streamNormalTask();
86 | }
87 |
88 | @OnClick(R.id.btn_start2)
89 | public void onClickStart2(final View v){
90 | this.streamLongTask();
91 | }
92 |
93 | //--------------------------------------------------
94 | // My Streams
95 | //--------------------------------------------------
96 |
97 | public void streamNormalTask(){
98 |
99 | this.startRunningNormalTask();
100 |
101 | subscription = getObservableOnNormalTask()
102 | .subscribeOn(Schedulers.io())
103 | .observeOn(AndroidSchedulers.mainThread())
104 | .subscribe(getObserverNormalTask());
105 | }
106 |
107 | public void streamLongTask(){
108 |
109 | this.startRunningLongTask();
110 |
111 | subscription = getObservableOnNormalTask()
112 | .startWith(getObservableOnLongTask(true))
113 | .subscribeOn(Schedulers.io())
114 | .observeOn(AndroidSchedulers.mainThread())
115 | .subscribe(getObserverLongTask());
116 | }
117 |
118 |
119 | // -------------------------------------------------------------
120 | // RXJava: Observable & Observer
121 | // -------------------------------------------------------------
122 |
123 | private Observable getObservableOnNormalTask() {
124 |
125 | return Observable.create(
126 | new Observable.OnSubscribe() {
127 | @Override
128 | public void call(Subscriber super Boolean> sub) {
129 | sub.onNext(Functions.normalRunningOperation());
130 | sub.onCompleted();
131 | }
132 | }
133 | );
134 | }
135 |
136 | private Observable getObservableOnLongTask(final Boolean isCombinedTask) {
137 | return Observable.create(
138 | new Observable.OnSubscribe() {
139 | @Override
140 | public void call(Subscriber super Boolean> sub) {
141 | sub.onNext(Functions.longRunningOperation(isCombinedTask));
142 | sub.onCompleted();
143 | }
144 | }
145 | );
146 | }
147 |
148 | //-------
149 |
150 | private Observer getObserverCounter() {
151 | return new Observer() {
152 |
153 | @Override
154 | public void onCompleted() { }
155 |
156 | @Override
157 | public void onError(Throwable e) { Log.e("TAG", "Error ! "+e.getMessage()); }
158 |
159 | @Override
160 | public void onNext(Integer value) { updateCounterDesign(value); }
161 | };
162 | }
163 |
164 | private Observer getObserverNormalTask() {
165 | return new Observer() {
166 |
167 | @Override
168 | public void onCompleted() { stopRunningNormalTask(); }
169 |
170 | @Override
171 | public void onError(Throwable e) { Log.e("TAG", "Error ! Man "+e.getMessage()); }
172 |
173 | @Override
174 | public void onNext(Boolean value) { }
175 | };
176 | }
177 |
178 | private Observer getObserverLongTask() {
179 | return new Observer() {
180 |
181 | @Override
182 | public void onCompleted() { }
183 |
184 | @Override
185 | public void onError(Throwable e) { Log.e("TAG", "Error ! Man "+e.getMessage()); }
186 |
187 | @Override
188 | public void onNext(Boolean haveToStartNormalTask) { updateLongTaskDesign(haveToStartNormalTask); }
189 | };
190 | }
191 |
192 | // -------------------------------------------------------------
193 | // Private funcs that handle design updates
194 | // -------------------------------------------------------------
195 |
196 | private void startRunningNormalTask(){
197 | Log.e("TAG", "Start normal task...");
198 | counterRunningTasks.onNext(counterRunningTasks.getValue()+1);
199 | counterNormalRunningTask++;
200 | if (progressNormal != null){
201 | progressNormal.setVisibility(View.VISIBLE);
202 | }
203 | }
204 |
205 | private void stopRunningNormalTask(){
206 | Log.e("TAG", "Stop normal task...");
207 | counterRunningTasks.onNext(counterRunningTasks.getValue()-1);
208 | counterNormalRunningTask--;
209 | if (counterNormalRunningTask == 0 ){
210 | if (progressNormal != null){
211 | progressNormal.setVisibility(View.GONE);
212 | }
213 | }
214 | }
215 |
216 | // ----------------
217 |
218 | private void startRunningLongTask(){
219 | Log.e("TAG", "Start long task...");
220 | counterRunningTasks.onNext(counterRunningTasks.getValue()+1);
221 | counterLongRunningTask++;
222 | if (progressLong != null){
223 | progressLong.setVisibility(View.VISIBLE);
224 | }
225 | }
226 |
227 | private void stopRunningLongTask(){
228 | Log.e("TAG", "Stop long task...");
229 | counterRunningTasks.onNext(counterRunningTasks.getValue()-1);
230 | counterLongRunningTask--;
231 | if (counterLongRunningTask == 0 ) {
232 | if (progressLong != null){
233 | progressLong.setVisibility(View.GONE);
234 | }
235 | }
236 | }
237 |
238 | // --------------
239 |
240 | private void updateLongTaskDesign(Boolean haveToStartNormalTask){
241 | if (haveToStartNormalTask){
242 | stopRunningLongTask();
243 | startRunningNormalTask();
244 | } else {
245 | stopRunningNormalTask();
246 | }
247 | }
248 |
249 | private void updateCounterDesign(Integer value){
250 | if (rootView != null){
251 | txtViewStateLong.setText("LONG TASK ("+counterLongRunningTask+")");
252 | txtViewStateNormal.setText("NORMAL TASK ("+counterNormalRunningTask+")");
253 | txtViewCounter.setText("Task(s) running: "+value.toString());
254 | if (value == 0){
255 | title.setText("Let's run the world ! Or at least tasks...");
256 | } else if (value == 1){
257 | title.setText("A task is running...");
258 | } else {
259 | title.setText(value+" tasks are running...");
260 | }
261 | }
262 | }
263 | }
264 |
--------------------------------------------------------------------------------