Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Architecture Components - Lifecycle library
Search
Masaki Ogata
May 29, 2017
Programming
3
2.3k
Architecture Components - Lifecycle library
a slide of architecture components about lifecycle library.
Masaki Ogata
May 29, 2017
Tweet
Share
More Decks by Masaki Ogata
See All by Masaki Ogata
Jetpack Composeで始めるServer Cache State
ogaclejapan
2
170
AbemaTVを支えるアプリの優しさ / abematv_devcon_2017
ogaclejapan
3
6.4k
How to keep data between orientation changes
ogaclejapan
7
2.5k
Your app name
ogaclejapan
1
2.8k
Flux de Relax :)
ogaclejapan
13
61k
Dagger2 has been released!
ogaclejapan
3
3.2k
Other Decks in Programming
See All in Programming
rails stats で紐解く ANDPAD のイマを支える技術たち
andpad
1
290
20年もののレガシープロダクトに 0からPHPStanを入れるまで / phpcon2024
hirobe1999
0
500
Amazon S3 NYJavaSIG 2024-12-12
sullis
0
100
「Chatwork」Android版アプリを 支える単体テストの現在
okuzawats
0
180
tidymodelsによるtidyな生存時間解析 / Japan.R2024
dropout009
1
790
PHPで学ぶプログラミングの教訓 / Lessons in Programming Learned through PHP
nrslib
3
290
Beyond ORM
77web
7
900
クリエイティブコーディングとRuby学習 / Creative Coding and Learning Ruby
chobishiba
0
3.9k
[JAWS-UG横浜 #76] イケてるアップデートを宇宙いち早く紹介するよ!
maroon1st
0
460
Security_for_introducing_eBPF
kentatada
0
110
menu基盤チームによるGoogle Cloudの活用事例~Application Integration, Cloud Tasks編~
yoshifumi_ishikura
0
110
Scalaから始めるOpenFeature入門 / Scalaわいわい勉強会 #4
arthur1
1
340
Featured
See All Featured
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
159
15k
YesSQL, Process and Tooling at Scale
rocio
169
14k
GraphQLとの向き合い方2022年版
quramy
44
13k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
26
1.5k
The Straight Up "How To Draw Better" Workshop
denniskardys
232
140k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
111
49k
For a Future-Friendly Web
brad_frost
175
9.4k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
33
2k
Bash Introduction
62gerente
608
210k
Measuring & Analyzing Core Web Vitals
bluesmoon
4
170
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
38
1.9k
Building Adaptive Systems
keathley
38
2.3k
Transcript
CA.apk #3 Google I/O 2017 ใࠂձ @CyberAgent Masaki Ogata ArchitectureComponents
Lifecycle library :)
ࣗݾհ Masaki Ogata CyberAgent, Inc. / AbemaTV, Inc. ogaclejapan @ogaclejapan
New
͍ͭʹ… ॳબ͠·ͨ͠
ॳI/O ŝŦŝŦŝŦŝŦᴸᴸᴸ ƅ㱼ƅ㲇 ƅ㱼ƅ㲇ƅ㱼ƅ)㲇ƅ㱼ƅ)ᴸᴸᴸᴸ!!
Google Keynote
Google Keynote
What’s new for Android TV
Single Codebase, Two Apps with Flutter and Firebase
Google Play Awards
Google Play Awards
None
None
allprojects { repositories { jcenter() maven { url 'https://maven.google.com' }
} } dependencies { compile "android.arch.lifecycle:runtime:1.0.0-alpha1" compile "android.arch.lifecycle:extensions:1.0.0-alpha1" annotationProcessor "android.arch.lifecycle:compiler: 1.0.0-alpha1" } 1. Add the Google Maven repository 2. Add Architecture Components - Lifecycle
Handling Lifecycles
ϥΠϑαΠΫϧΛͭ͜ͱΛࣔ͢ΠϯλϑΣʔε • LifecycleOwner public interface LifecycleOwner { Lifecycle getLifecycle(); }
• LifecycleRegistryOwner (※Temporary) public interface LifecycleRegistryOwner extends LifecycleOwner { @Override LifecycleRegistry getLifecycle(); }
ݱঢ়ͰLifecycleActivity, LifecycleFragment, LifecycleServiceΫϥε͕ϥΠϒϥϦʹ༻ҙ͞Ε͍ͯΔ public class LifecycleActivity extends FragmentActivity implements LifecycleRegistryOwner
{ private final LifecycleRegistry mRegistry = new LifecycleRegistry(this); @Override public LifecycleRegistry getLifecycle() { return mRegistry; } } ※Alpha൛ͩͱAppCompatActivity൛࣮͍ͯ͠ͳ͍
AppCompatActivityͰLifecycleΛࢼ͍ͨ͠ਓࣗલͰ public class LifecycleCompatActivity extends AppCompatActivity implements LifecycleRegistryOwner { private
final LifecycleRegistry mRegistry = new LifecycleRegistry(this); @Override public LifecycleRegistry getLifecycle() { return mRegistry; } } Ϋϥεͷ࣮ίʔυLifecycleActivityͱશ͘ಉ͡ɻ ͜Ε͚ͩͰࣗಈతʹϥΠϑαΠΫϧʹԠͯͪ͡ΌΜͱಈ͘
ϥΠϑαΠΫϧΛ؍ଌ͢ΔͨΊͷΠϯλϑΣʔε • LifecycleObserver public interface LifecycleObserver { }
ϥΠϑαΠΫϧΛ؍ଌ͢ΔͨΊͷΠϯλϑΣʔε • LifecycleObserver public interface LifecycleObserver { } public class
FooObserver implements LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) void start() { /* Start something. */ } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { /* Stop something. */ } }
͋ͱLifecycleOwnerͷLifecycleΫϥεʹadd͢Δ͚ͩ public class FooActivity extends LifecycleActivity { @Override protected void
onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... getLifecycle().addObserver(new FooObserver()); } }
͋ͱLifecycleOwnerͷLifecycleΫϥεʹadd͢Δ͚ͩ public class FooActivity extends LifecycleActivity { @Override protected void
onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... getLifecycle().addObserver(new FooObserver()); } } FooActivity: ⇠ onStart [0ms] FooObserver: Start something. FooActivity: ⇢ onResume() ... FooActivity: ⇠ onPause [0ms] FooObserver: Stop something. FooActivity: ⇢ onStop() ActivityͷϥΠϑαΠΫϧʹϩά ΛࠐΜͰ࣮ߦͯ͠ΈΔͱ…
“Lifecycle-aware components” public class FooObserver implements LifecycleObserver { public FooObserver(Lifecycle
lifecycle) { ... this.lifecycle.addObserver(this); } @OnLifecycleEvent(Lifecycle.Event.ON_START) void start() { /* Start something. */ } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void stop() { /* "Stop something." */ } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void cleanup() { lifecycle.removeObserver(this); } }
LifecycleΫϥε public abstract class Lifecycle { public abstract void addObserver(LifecycleObserver
observer); public abstract void removeObserver(LifecycleObserver observer); public abstract State getCurrentState(); public enum Event { ON_CREATE, ON_START, ...ON_ANY } public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast(State state) { return compareTo(state) >= 0; } } }
LifecycleΫϥε public abstract class Lifecycle { public abstract void addObserver(LifecycleObserver
observer); public abstract void removeObserver(LifecycleObserver observer); public abstract State getCurrentState(); public enum Event { ON_CREATE, ON_START, ...ON_ANY } public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast(State state) { return compareTo(state) >= 0; } } }
https://developer.android.com/topic/libraries/architecture/lifecycle.html class MyLocationListener implements LifecycleObserver { public void enable() {
enabled = true; if (lifecycle.getState().isAtLeast(STARTED)) { // connect if not connected } }
Deep dive into Lifecycles
1. LifecycleObserverͷ෦࣮ʁ
AnnotationProcessorʹΑΓࣗಈੜ͞ΕͨFooObserver public class FooObserver_LifecycleAdapter implements GenericLifecycleObserver { final FooObserver mReceiver;
... @Override public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) { if (event == Lifecycle.Event.ON_START) { mReceiver.start(); } if (event == Lifecycle.Event.ON_STOP) { mReceiver.stop(); } } } ※GenericLifecycleObserver@hideͳΫϥε
LifecycleRegistryΫϥε public class LifecycleRegistry extends Lifecycle { @Override public void
addObserver(LifecycleObserver observer) { ObserverWithState observerWithState = new ObserverWithState(observer); mObserverSet.putIfAbsent(observer, observerWithState); observerWithState.sync(); } ... class ObserverWithState { private State mObserverCurrentState = INITIALIZED; private GenericLifecycleObserver mCallback; ObserverWithState(LifecycleObserver observer) { mCallback = Lifecycling.getCallback(observer); } }
LifecycleRegistryΫϥε public class LifecycleRegistry extends Lifecycle { @Override public void
addObserver(LifecycleObserver observer) { ObserverWithState observerWithState = new ObserverWithState(observer); mObserverSet.putIfAbsent(observer, observerWithState); observerWithState.sync(); } ... class ObserverWithState { private State mObserverCurrentState = INITIALIZED; private GenericLifecycleObserver mCallback; ObserverWithState(LifecycleObserver observer) { mCallback = Lifecycling.getCallback(observer); } }
LifecyclingΫϥε class Lifecycling { static GenericLifecycleObserver getCallback(Object object) { ...
final Class<?> klass = object.getClass(); ... cachedConstructor = getGeneratedAdapterConstructor(klass); ... return new ReflectiveGenericLifecycleObserver(object); ... static String getAdapterName(String className) { return className.replace(".", "_") + "_LifecycleAdapter"; }
2. Lifecycle.Eventͷൃ৴ҰମͲ͔͜Βʁ
AndroidManifest (packaged)ʹո͛͠ͳprovider͕… <manifest ...> <application ...> ... <provider android:name="android.arch.lifecycle.LifecycleRuntimeTroja nProvider"
android:exported="false" android:multiprocess="true" android:authorities="com.ogaclejapan.samples.lifecycle- trojan" /> </application> </manifest> (*´ŋωŋ`)̾̌˓( ͤΊͯެࣜυΩϡϝϯτʹॻ͍ͯ͘ΕΑ͒͒ɻɻɻ)
LifecycleRuntimeTrojanProviderΫϥε public class LifecycleRuntimeTrojanProvider extends ContentProvider { @Override public boolean
onCreate() { LifecycleDispatcher.init(getContext()); ProcessLifecycleOwner.init(getContext()); return true; } ... Firebase͕ར༻͍ͯ͠ΔContentProviderΛར༻ͨ͠ॳظԽHack ʢ҉తʹApplicationͷonCreateΑΓઌʹॳظԽΛ࣮ߦͰ͖Δʣ ʮHow does Firebase initialize on Android?ʯ https://firebase.googleblog.com/2016/12/how-does-firebase-initialize-on-android.html
LifecycleDispatcherΫϥεͰ͍ͬͯΔ͜ͱʢͬ͘͟Γʣ • initॲཧͰActivityLifecycleCallbacksίʔϧόοΫొ • onActivityCreatedͰ”ReportFragment”ͷՃͱ FragmentLifecycleCallbacksίʔϧόοΫొ • onFragmentCreatedͰFragment͕ LifecycleRegistryOwnerΛ࣮͍ͯ͠Ε ”DestructionReportFragment”ΛՃ
• ֤LifecycleCallbacksͰLifecycleRegistryOwnerΛ࣮ ͍ͯ͠ΕLifecycleRegistryʹରͯ͠”markState()” ͱ”handleLifecycleEvent()”ͷߋ৽ΛҰ෦୲͏
LifecycleDispatcherΫϥεͰ͍ͬͯΔ͜ͱʢͬ͘͟Γʣ • initॲཧͰActivityLifecycleCallbacksίʔϧόοΫొ • onActivityCreatedͰ”ReportFragment”ͷՃͱ FragmentLifecycleCallbacksίʔϧόοΫొ • onFragmentCreatedͰFragment͕ LifecycleRegistryOwnerΛ࣮͍ͯ͠Ε ”DestructionReportFragment”ΛՃ
• ֤LifecycleCallbacksͰLifecycleRegistryOwnerΛ࣮ ͍ͯ͠ΕLifecycleRegistryʹରͯ͠”markState()” ͱ”handleLifecycleEvent()”ͷߋ৽ΛҰ෦୲͏
LifecycleDispatcherΫϥεͰ͍ͬͯΔ͜ͱʢͬ͘͟Γʣ • initॲཧͰActivityLifecycleCallbacksίʔϧόοΫొ • onActivityCreatedͰ”ReportFragment”ͷՃͱ FragmentLifecycleCallbacksίʔϧόοΫొ • onFragmentCreatedͰFragment͕ LifecycleRegistryOwnerΛ࣮͍ͯ͠Ε ”DestructionReportFragment”ΛՃ
• ֤LifecycleCallbacksͰLifecycleRegistryOwnerΛ࣮ ͍ͯ͠ΕLifecycleRegistryʹରͯ͠”markState()” ͱ”handleLifecycleEvent()”ͷߋ৽ΛҰ෦୲͏
LifecycleDispatcherΫϥεͰ͍ͬͯΔ͜ͱʢͬ͘͟Γʣ • initॲཧͰActivityLifecycleCallbacksίʔϧόοΫొ • onActivityCreatedͰ”ReportFragment”ͷՃͱ FragmentLifecycleCallbacksίʔϧόοΫొ • onFragmentCreatedͰFragment͕ LifecycleRegistryOwnerΛ࣮͍ͯ͠Ε ”DestructionReportFragment”ΛՃ
• ֤LifecycleCallbacksͰLifecycleRegistryOwnerΛ࣮ ͍ͯ͠ΕLifecycleRegistryʹରͯ͠”markState()” ͱ”handleLifecycleEvent()”ͷߋ৽ΛҰ෦୲͏
ReportFragmentΫϥε public class ReportFragment extends Fragment { public void onActivityCreated(Bundle
savedInstanceState) { ... dispatch(Lifecycle.Event.ON_CREATE); } ... private void dispatch(Lifecycle.Event event) { if (getActivity() instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner) getActivity()).getLifecycle().handleLifecycleEvent(event); } } LifecycleRegistryOwnerΛ࣮ͨ͠ActivityͷϥΠϑαΠΫϧมߋ Πϕϯτͯ͢ReportFragmentͰݺΕ͍ͯΔ
͏ʔΜɺ૾Ҏ্ʹཪͰ৭ʑͬͯͨɻɻ
LiveData<T>
LiveDataΫϥε • ͷߋ৽Λ҆શʹObserver௨Մೳ -> LifecycleOwnerͷState͕STARTED or RESUMED࣌ͷΈ௨ • Lifecycle-aware components.
-> LifecycleOwnerͷState͕DESTROYED࣌observerΛࣗಈղআ public abstract class LiveData<T> { @MainThread public void observe(LifecycleOwner owner, Observer<T> observer) { ... } protected void postValue(T value) { ... } @MainThread protected void setValue(T value) { ... } public T getValue() { ... } ... }
LiveDataͷΈ State: STARTED or RESUMED State: CREATED Observer LiveData setValue(“Foo”)
: version = 0 observe() onChange(“Foo”) setValue(“Bar”) : version = 1 pending onChange(“Bar”) lastVersion = 0 lastVersion = 1 setValue(“CA”) : version = 2 lastVersion = -1 initial : version = -1 setValue(“apk”) : version = 3 onChange(“apk”) lastVersion = 3 pending ※version͕ಉ͡ͳͷͰ௨͠ͳ͍
MutableLiveDataΫϥε public class MutableLiveData<T> extends LiveData<T> { @Override public void
postValue(T value) { super.postValue(value); } @Override public void setValue(T value) { super.setValue(value); } } • postValue() / setValue()Λpublicείʔϓมߋ -> ObservableFieldBehaviorSubjectΈ͍ͨͳͷมߋݕ͕Ͱ ͖ΔϓϩύςΟͱͯ͑ͦ͠͏
TimerLiveDataΫϥε (Custom) public class TimerLiveData extends LiveData<Long> { private final
Runnable TimeUpdater = new Runnable() { @Override public void run() { setValue(elapsedTime += 1000L); handler.postDelayed(TimeUpdater, 1000L); } }; private final Handler handler = new Handler(); private long elapsedTime = 0L; @Override protected void onActive() { handler.postDelayed(TimeUpdater, 1000L); } @Override protected void onInactive() { handler.removeCallbacks(TimeUpdater); } }
TimerLiveDataΫϥε (Custom) public class TimerLiveData extends LiveData<Long> { private final
Runnable TimeUpdater = new Runnable() { @Override public void run() { setValue(elapsedTime += 1000L); handler.postDelayed(TimeUpdater, 1000L); } }; private final Handler handler = new Handler(); private long elapsedTime = 0L; @Override protected void onActive() { handler.postDelayed(TimeUpdater, 1000L); } @Override protected void onInactive() { handler.removeCallbacks(TimeUpdater); } }
LiveData<String> userName = Transformations.map(userLiveData, user -> { user.name + "
" + user.lastName }); Transformations MediatorLiveData https://developer.android.com/reference/android/arch/lifecycle/MediatorLiveData.html https://developer.android.com/reference/android/arch/lifecycle/Transformations.html -> ಠࣗͳTransformationsΛ৽ͨʹఆٛ͢Δͱ͖ʹ͑Δ -> LiveDataͷΛՃ͢Δ (ݱঢ়map, switchMapͷΈ)
ViewModel
ViewModelΫϥε public abstract class ViewModel { protected void onCleared() {
} } ViewModelProviders.of(activity) .get(FooViewModel.class) ViewModelStores.of(activity) HolderFragmentੜ -> setRetainInstance(true)
https://speakerdeck.com/ogaclejapan/how-to-keep-data-between-orientation-changes
ViewModelΫϥεར༻࣌ͷҙ • Activity࠶ੜΛލ͍Ͱσʔλ͕อ࣋͞ΕΔͷͰɺActivity ViewɺResourceͳͲΛอ࣋͢ΔͱϝϞϦϦʔΫ͢Δ :( Ͳ͏ͯ͠ViewModelͰContextΛ͍͍ͨͱ͖ʹApplication ΫϥεΛอ࣋͢ΔAndroidViewModelΛ͍·͠ΐ͏ public class AndroidViewModel
extends ViewModel { private Application mApplication; public AndroidViewModel(Application application) { mApplication = application; } public <T extends Application> T getApplication() { return (T) mApplication; } }
Architecture componentsͰਪ͞ΕΔΞʔΩςΫνϟ https://developer.android.com/topic/libraries/architecture/guide.html#the_final_architecture
ࢀߟࢿྉ
• ެࣜΨΠυ https://developer.android.com/topic/libraries/architecture/index.html • ެࣜαϯϓϧ https://github.com/googlesamples/android-architecture-components Architecture Components ࢀߟϦϯΫ •
I/O ηογϣϯಈը Architecture Components - Introduction https://www.youtube.com/watch?v=FrteWKKVyzI Architecture Components - Solving the Lifecycle Problem https://www.youtube.com/watch?v=bEKNi1JOrNs
ࠓޙʹظʂʂ