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
Observable vs. LiveData
Search
Sponsored
·
SiteGround - Reliable hosting with speed, security, and support you can count on.
→
Seiya Kokushi
February 27, 2018
Technology
1.3k
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Observable vs. LiveData
Seiya Kokushi
February 27, 2018
More Decks by Seiya Kokushi
See All by Seiya Kokushi
OS 標準のデザインシステムを超えて - より柔軟な Flutter テーマ管理 | FlutterKaigi 2024
ronnnnn
0
1.8k
Kotlin/NativeのNew Memory Managerに移行しよう | Kotlin Fest 2022
ronnnnn
0
840
Kotlin Multiplatform MobileのおさらいとABEMAでのマルチプラットフォーム対応 | CA BASE NEXT 2022
ronnnnn
0
260
Compose Multiplatformってどうなんだろう? | Flutter × Kotlin Multiplatform by CyberAgent #7
ronnnnn
0
1k
Multiplatform Engineering Roadmap for the Future | ABEMA Developer Conference 2021
ronnnnn
0
130
エンジニアとしてのプロダクト貢献
ronnnnn
2
100k
事業を伸ばすためにエンジニアとして何ができるか
ronnnnn
3
2.3k
Other Decks in Technology
See All in Technology
Forza Horizon 6 のテレメトリ機能で 自動運転に使えそうな学習データを集める話
henjin0
0
150
LLM・AIエージェントシステムベストプラクティス
shibuiwilliam
2
520
オートロックマンションなのに、各部屋は施錠なし!? 攻撃者が組織内ネットワークで大暴れする理由 / The Front Door Is Locked, but the Rooms Are Wide Open: Why Attackers Move Freely Inside Enterprise Networks
nttcom
1
1.6k
DatadogのBits Chatが開発組織にもたらしたもの / What Bits Chat Has Brought Us
sms_tech
0
110
メルカリのグローバルアプリで挑んだ AlloyDB 運用と課題解決の実践記
hatappi
0
240
SO-101×VLAによる3色キューブのピック&プレース
abeja
0
160
Contract One Engineering Unit 紹介資料
sansan33
PRO
0
19k
20260608_Codexの可能性_ノンプログラマー向け_大城追記
doradora09
PRO
0
780
Master Dataグループ紹介資料
sansan33
PRO
1
4.8k
攻撃と防御で学ぶAI時代のプロダクトセキュリティ演習
recruitengineers
PRO
7
2.2k
【CEDEC2026】『ウマ娘 プリティーダービー』 英語版のキャラクターの方言や口調をローカライズするための創造的アプローチ
cygames
PRO
1
200
モダンフロントエンド 開発研修
recruitengineers
PRO
3
560
Featured
See All Featured
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
Facilitating Awesome Meetings
lara
57
7.1k
Measuring Dark Social's Impact On Conversion and Attribution
stephenakadiri
2
250
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
210
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
Building an army of robots
kneath
306
46k
4 Signs Your Business is Dying
shpigford
187
22k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
17k
Balancing Empowerment & Direction
lara
6
1.2k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
690
AI Search: Implications for SEO and How to Move Forward - #ShenzhenSEOConference
aleyda
1
1.3k
<Decoding/> the Language of Devs - We Love SEO 2024
nikkihalliwell
1
280
Transcript
Observable vs. LiveData CA.apk #5 Seiya Kokushi
Seiya Kokushi ronnnnn ronnnnn_jp
Motivation
ある日のMTGにて.. それじゃあ、ViewとViewModelは Observableでやりとりしましょ! さんせ〜い!! よーし、新しいアーキテクチャは MVVMを採用するぞ〜!
な、なぜLiveDataじゃないんだ!! そもそも、ObservableとLiveDataの 違いって何だ〜!!!
Overview
✂ ✂ Observable LiveData - android.databinding - interface - BaseObservable
ObservableField<T> ObservableXxx ObservableListなど - bindable - android.arch.lifecycle - abstract class - MutableLiveData<T>など - lifecycle aware
Pros and cons
View ViewModel Observable LiveData Data action fetch flowable observe update
Observable class MainViewModel @Inject constructor( private val randomUseCase: RandomUseCase )
: ViewModel() { val title: ObservableField<String> = ObservableField("") val imageUrl: ObservableField<String> = ObservableField("") … init { randomUseCase.observe() .subscribeOn(Schedulers.io()) .subscribe({ randomData -> title.set(randomData.data.title) imageUrl.set(randomData.data.images.downsizedMedium.url) }) .let { compositeDisposable.add(it) } fetchRandomData() } … } 監視したいオブジェクトを Observableで宣言 値が流れてきたら 値をObservableにセット
<layout > <data> <variable name="viewModel" type="com.ronnnnn.androidsamples.ui.MainViewModel" /> </data> <RelativeLayout >
<Button android:onClick="@{() -> viewModel.updateRandom()}” /> <TextView android:text="@{viewModel.title}" /> <ImageView imageUrl="@{viewModel.imageUrl}" /> </RelativeLayout> </layout> 値に変更があったら viewのpropertyが変更される Observable
Observable - DataBindingを最大限活用できる - オブジェクトに変更があった時のみ、値を通知する public class ObservableField<T> extends BaseObservable
implements Serializable { … private T mValue; … /** * Set the stored value. */ public void set(T value) { if (value != mValue) { mValue = value; notifyChange(); } } }
Observable - Lifecycle Awareじゃない - メモリリーク..? - 値変更のlistenerが
WeakReferenceを継承 - 画面遷移には不向き - 最新の値をキャッシュする ので、戻るとまた遷移する private static class WeakListener<T> extends WeakReference<ViewDataBinding> { private final ObservableReference<T> mObservable; protected final int mLocalFieldId; private T mTarget; … public boolean unregister() { boolean unregistered = false; if (mTarget != null) { mObservable.removeListener(mTarget); unregistered = true; } mTarget = null; return unregistered; } … protected ViewDataBinding getBinder() { ViewDataBinding binder = get(); if (binder == null) { unregister(); // The binder is dead } return binder; } }
LiveData class MainViewModel @Inject constructor( private val randomUseCase: RandomUseCase )
: ViewModel() { val title: MutableLiveData<String> = MutableLiveData() val imageUrl: MutableLiveData<String> = MutableLiveData() … init { randomUseCase.observe() .subscribeOn(Schedulers.io()) .subscribe({ randomData -> title.postValue(randomData.data.title) imageUrl.postValue(randomData.data.images.downsizedMedium.url) }) .let { compositeDisposable.add(it) } fetchRandomData() } … } 監視したいオブジェクトを LiveDataで宣言 値が流れてきたら 値をLiveDataにpost
class MainActivity : AppCompatActivity() { … override fun onCreate(savedInstanceState: Bundle?)
{ super.onCreate(savedInstanceState) component.inject(this) val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main).apply { viewModel = mainViewModel } mainViewModel.imageUrl.observe(this, Observer { it ?: return@Observer binding.gifImageView.load(it) }) mainViewModel.title.observe(this, Observer { it ?: return@Observer binding.titleTextView.text = it }) } … } 値が通知されたら viewのpropertyを更新する LiveData
- DataBindingを最大限活用できない - オブジェクトに変更がなくても、値を通知する LiveData protected void postValue(T value) {
boolean postTask; synchronized (mDataLock) { postTask = mPendingData == NOT_SET; mPendingData = value; } if (!postTask) { return; } ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable); } @MainThread protected void setValue(T value) { assertMainThread("setValue"); mVersion++; mData = value; dispatchingValue(null); }
LiveData - Lifecycle Aware - 厳密な画面遷移には不向き - LiveDataはonPauseの後に購読解除される -
onSaveInstanceState後の画面遷移を再現できない googlesamples/android-architecture-components/issues/63
Plus one
None
None
None
sample project ronnnnn/AndroidSamples observable livedata livedatabinding (AS 3.1 canary 6+)