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
830
Kotlin Multiplatform MobileのおさらいとABEMAでのマルチプラットフォーム対応 | CA BASE NEXT 2022
ronnnnn
0
250
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.2k
Other Decks in Technology
See All in Technology
10年間のブログ発信を振り返って見えたWebアプリケーションエンジニアとしての軌跡
stefafafan
0
170
ロボティクスの技術 / Robotics Technology
ks91
PRO
0
110
GitHub Copilot 最新アップデート – 「一歩先」の実践活用術
moulongzhang
5
1.5k
アンオフィシャルな、オフィシャルからのお願い
wyamazak_devrel
0
140
PostgreSQL 19 新機能概要 OSC Hokkaido 2026
nori_shinoda
0
150
Oracle AI Database@AWS:サービス概要のご紹介
oracle4engineer
PRO
4
3k
GitHub Copilot app最速の発信の裏側
tomokusaba
1
190
AIネイティブな開発のサプライチェーンリスク対策 〜激動の開発現場でリスクに立ち向かう〜【ZennFes】
cscengineer
PRO
2
140
AIAU_UMEMOGU_ninomiya_slide
ninomiya_ii
0
240
小さく始める AI 活用推進 ― 日経電子版 Web チームの事例/nikkei-tech-talk47
nikkei_engineer_recruiting
0
300
AIのReact習熟度を測る
uhyo
2
650
MUSUBI 田中裕一『AIと共に行う「しごとのリデザイン」- スモールバックオフィス編』AI Ops Lab #4
musubi
0
270
Featured
See All Featured
HTML-Aware ERB: The Path to Reactive Rendering @ RubyCon 2026, Rimini, Italy
marcoroth
1
200
Exploring anti-patterns in Rails
aemeredith
3
410
Getting science done with accelerated Python computing platforms
jacobtomlinson
2
240
GitHub's CSS Performance
jonrohan
1033
470k
30 Presentation Tips
portentint
PRO
1
330
Measuring & Analyzing Core Web Vitals
bluesmoon
9
870
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
2.9k
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
170
Paper Plane
katiecoart
PRO
1
51k
The Pragmatic Product Professional
lauravandoore
37
7.3k
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
1.2k
How Fast Is Fast Enough? [PerfNow 2025]
tammyeverts
3
610
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+)