Skip to content

Commit ae93f34

Browse files
author
Kaushik Gopal
committed
feat: wip add a persist over rotation fragment
1 parent a0b2e2d commit ae93f34

7 files changed

Lines changed: 278 additions & 1 deletion

File tree

‎app/src/main/java/com/morihacky/android/rxjava/MainActivity.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ protected void onCreate(Bundle savedInstanceState) {
2424

2525
if (savedInstanceState == null) {
2626
getSupportFragmentManager().beginTransaction()
27-
.replace(android.R.id.content, new MainFragment(), this.toString())
27+
//.replace(android.R.id.content, new MainFragment(), this.toString())
28+
.replace(android.R.id.content, new RotationPersistFragment(), this.toString())
2829
.commit();
2930
}
3031
}

‎app/src/main/java/com/morihacky/android/rxjava/MainFragment.java‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,4 +148,15 @@ public void demoExponentialBackoff() {
148148
ExponentialBackoffFragment.class.toString())
149149
.commit();
150150
}
151+
152+
@OnClick(R.id.btn_demo_rotation_persist)
153+
public void demoRotationPersist() {
154+
getActivity().getSupportFragmentManager()
155+
.beginTransaction()
156+
.addToBackStack(RotationPersistFragment.class.toString())
157+
.replace(android.R.id.content,
158+
new RotationPersistFragment(),
159+
RotationPersistFragment.class.toString())
160+
.commit();
161+
}
151162
}
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
package com.morihacky.android.rxjava;
2+
3+
import android.os.Bundle;
4+
import android.os.Handler;
5+
import android.support.annotation.Nullable;
6+
import android.support.v4.app.FragmentManager;
7+
import android.view.LayoutInflater;
8+
import android.view.View;
9+
import android.view.ViewGroup;
10+
import android.widget.ListView;
11+
import butterknife.ButterKnife;
12+
import butterknife.InjectView;
13+
import butterknife.OnClick;
14+
import com.morihacky.android.rxjava.wiring.LogAdapter;
15+
import java.util.ArrayList;
16+
import java.util.List;
17+
import rx.Observable;
18+
import rx.Observer;
19+
import rx.subscriptions.CompositeSubscription;
20+
import timber.log.Timber;
21+
22+
import static android.os.Looper.getMainLooper;
23+
24+
public class RotationPersistFragment
25+
extends BaseFragment
26+
implements RotationPersistWorkerFragment.IAmYourMaster {
27+
28+
@InjectView(R.id.list_threading_log) ListView _logList;
29+
private LogAdapter _adapter;
30+
private List<String> _logs;
31+
32+
private CompositeSubscription _subscriptions = new CompositeSubscription();
33+
34+
@Override
35+
public void onResume() {
36+
super.onResume();
37+
_subscriptions = RxUtils.getNewCompositeSubIfUnsubscribed(_subscriptions);
38+
}
39+
40+
@Override
41+
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
42+
super.onActivityCreated(savedInstanceState);
43+
_setupLogger();
44+
}
45+
46+
@Override
47+
public View onCreateView(LayoutInflater inflater,
48+
@Nullable ViewGroup container,
49+
@Nullable Bundle savedInstanceState) {
50+
View layout = inflater.inflate(R.layout.fragment_rotation_persist, container, false);
51+
ButterKnife.inject(this, layout);
52+
return layout;
53+
}
54+
55+
@Override
56+
public void onPause() {
57+
super.onPause();
58+
59+
RxUtils.unsubscribeIfNotNull(_subscriptions);
60+
}
61+
62+
// -----------------------------------------------------------------------------------
63+
64+
@OnClick(R.id.btn_rotate_persist)
65+
public void startRetryingWithExponentialBackoffStrategy() {
66+
_logs = new ArrayList<>();
67+
_adapter.clear();
68+
69+
String FRAG_TAG = RotationPersistWorkerFragment.class.getName();
70+
FragmentManager fm = getActivity().getSupportFragmentManager();
71+
RotationPersistWorkerFragment frag =//
72+
(RotationPersistWorkerFragment) fm.findFragmentByTag(FRAG_TAG);
73+
74+
if (frag == null) {
75+
Timber.d("---- never created frag before");
76+
77+
// we've never created the frag before
78+
frag = new RotationPersistWorkerFragment();
79+
fm.beginTransaction().add(frag, FRAG_TAG).commit();
80+
} else {
81+
Timber.d("---- Worker frag already spawned");
82+
}
83+
}
84+
85+
@Override
86+
public void observeResults(Observable<Integer> ints) {
87+
Timber.d("observable instance ints %s", ints.toString());
88+
89+
_subscriptions.add(ints.subscribe(new Observer<Integer>() {
90+
@Override
91+
public void onCompleted() {
92+
_log("Observable is complete");
93+
}
94+
95+
@Override
96+
public void onError(Throwable e) {
97+
Timber.e(e, "Error in worker demo frag observable");
98+
_log("Dang! something went wrong.");
99+
}
100+
101+
@Override
102+
public void onNext(Integer integer) {
103+
_log(String.format("Worker frag spits out - %d", integer));
104+
}
105+
}));
106+
}
107+
108+
// -----------------------------------------------------------------------------------
109+
110+
private void _setupLogger() {
111+
_logs = new ArrayList<>();
112+
_adapter = new LogAdapter(getActivity(), new ArrayList<String>());
113+
_logList.setAdapter(_adapter);
114+
}
115+
116+
private void _log(String logMsg) {
117+
_logs.add(0, logMsg);
118+
119+
// You can only do below stuff on main thread.
120+
new Handler(getMainLooper()).post(new Runnable() {
121+
122+
@Override
123+
public void run() {
124+
_adapter.clear();
125+
_adapter.addAll(_logs);
126+
}
127+
});
128+
}
129+
130+
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package com.morihacky.android.rxjava;
2+
3+
import android.app.Activity;
4+
import android.os.Bundle;
5+
import android.support.v4.app.Fragment;
6+
import java.util.List;
7+
import java.util.concurrent.TimeUnit;
8+
import rx.Observable;
9+
import rx.functions.Func1;
10+
import timber.log.Timber;
11+
12+
public class RotationPersistWorkerFragment
13+
extends Fragment {
14+
15+
private Observable<Integer> _intsObservable;
16+
private IAmYourMaster _masterFrag;
17+
18+
/**
19+
* hold a refernce to the activity -> caller fragment
20+
* this way when the worker frag kicks off
21+
* we can talk back to the master and send results
22+
*/
23+
@Override
24+
public void onAttach(Activity activity) {
25+
super.onAttach(activity);
26+
27+
_masterFrag = (RotationPersistFragment) getActivity().getSupportFragmentManager()
28+
.findFragmentByTag(RotationPersistFragment.class.getName());
29+
30+
List<Fragment> frags = ((MainActivity) activity).getSupportFragmentManager().getFragments();
31+
32+
Timber.d("---- there are currently %d fragments attached", frags.size());
33+
34+
for (Fragment f : frags) {
35+
if (f instanceof IAmYourMaster) {
36+
_masterFrag = (IAmYourMaster) f;
37+
}
38+
}
39+
40+
if (_masterFrag == null) {
41+
throw new ClassCastException("We did not find a master who can understand us :( !");
42+
}
43+
}
44+
45+
/**
46+
* This method will only be called once when the retained
47+
* Fragment is first created.
48+
*/
49+
@Override
50+
public void onCreate(Bundle savedInstanceState) {
51+
super.onCreate(savedInstanceState);
52+
53+
// Retain this fragment across configuration changes.
54+
setRetainInstance(true);
55+
56+
57+
if (_intsObservable != null) {
58+
return;
59+
}
60+
61+
// Create and execute the "Hot" observable
62+
Timber.d("---- Creating a new ints observable");
63+
_intsObservable =//
64+
Observable.interval(1, TimeUnit.SECONDS)//
65+
.map(new Func1<Long, Integer>() {
66+
@Override
67+
public Integer call(Long aLong) {
68+
return aLong.intValue();
69+
}
70+
})//
71+
.take(20)// cause i don't want this thing to run indefinitely
72+
.share(); // we need a "hot" observable for demoing the example
73+
}
74+
75+
/**
76+
* The Worker fragment has started doing it's thing
77+
*/
78+
@Override
79+
public void onStart() {
80+
super.onStart();
81+
_masterFrag.observeResults(_intsObservable);
82+
}
83+
84+
/**
85+
* Set the callback to null so we don't accidentally leak the
86+
* Activity instance.
87+
*/
88+
@Override
89+
public void onDetach() {
90+
super.onDetach();
91+
_masterFrag = null;
92+
}
93+
94+
public interface IAmYourMaster {
95+
void observeResults(Observable<Integer> ints);
96+
}
97+
}

‎app/src/main/res/layout/fragment_main.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,5 +93,11 @@
9393
android:layout_width="match_parent"
9494
android:text="@string/btn_demo_exponential_backoff"
9595
/>
96+
<Button
97+
android:id="@+id/btn_demo_rotation_persist"
98+
android:layout_height="wrap_content"
99+
android:layout_width="match_parent"
100+
android:text="@string/btn_demo_rotation_persist"
101+
/>
96102
</LinearLayout>
97103
</ScrollView>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
3+
<LinearLayout
4+
android:orientation="vertical"
5+
android:layout_height="match_parent"
6+
android:layout_width="match_parent"
7+
xmlns:android="http://schemas.android.com/apk/res/android"
8+
>
9+
10+
<TextView
11+
android:layout_height="wrap_content"
12+
android:layout_width="match_parent"
13+
android:padding="10dp"
14+
android:gravity="center"
15+
android:text="@string/msg_demo_rotation_persist"
16+
/>
17+
18+
<Button
19+
android:id="@+id/btn_rotate_persist"
20+
android:layout_height="wrap_content"
21+
android:layout_width="match_parent"
22+
android:text="Start operation"
23+
/>
24+
25+
<ListView
26+
android:id="@+id/list_threading_log"
27+
android:layout_height="match_parent"
28+
android:layout_width="match_parent"
29+
/>
30+
</LinearLayout>

‎app/src/main/res/values/strings.xml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
<string name="btn_demo_pseudocache">Pseudo cache using concat</string>
1919
<string name="btn_demo_timing">Variations of timing/intervals/delays</string>
2020
<string name="btn_demo_exponential_backoff">Exponential backoff</string>
21+
<string name="btn_demo_rotation_persist">Rotation persist</string>
2122

2223
<string name="msg_demo_concurrency_schedulers">This is a demo of how long running operations can be offloaded to a background thread. After the operation is done, we resume back on the main thread. All using RxJava! \n\n To really see this shine. Hit the button multiple times and see how the button click which is a ui operation is never blocked because the long operation only runs in the background</string>
2324
<string name="msg_demo_buffer">This is a demo of how events can be accumulated using the "buffer" operation. Tap the button below repetitively and you will notice in the logs that button taps are collected over a span of 2s and printed below.</string>
@@ -31,4 +32,5 @@
3132
<string name="msg_demo_rxbus_1">Tap on the below button and RxBus will listen to the events</string>
3233
<string name="msg_demo_form_comb_latest">Monitor the state of multiple observables with the combineLatest operator. Only after all the 3 inputs contain valid entries will the submit button light up</string>
3334
<string name="msg_demo_timing">BTN 1: run single task once (after 2s complete)\nBTN 2: run task every 1s (start delay of 1s) toggle \nBTN 3: run task every 1s (start immediately) toggle \nBTN 4: run task 5 times every 3s (then complete)</string>
35+
<string name="msg_demo_rotation_persist">This is an example of starting an Observable and using the result across rotations. There are many ways to do this, we use a retained fragment in this example</string>
3436
</resources>

0 commit comments

Comments
 (0)