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
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.9k
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
140
エンジニアとしてのプロダクト貢献
ronnnnn
2
100k
事業を伸ばすためにエンジニアとして何ができるか
ronnnnn
3
2.3k
Other Decks in Technology
See All in Technology
DMMブックスのNext.js化を加速させるAI活用 / Migrating DMM Books to Next.js with AI
kentarom
1
330
PM領域でのAI Agentの活用
lycorptech_jp
PRO
0
270
PdMをやめて、 "プロダクトビルダー"という 働き方に変えました / PdM to Product Builder
shikichee
2
710
AIで仕事のやり方を変える
matsu7874
1
490
Self Healing Rollouts: Automating Production Fixes with Agentic AI
kdubois
0
150
Jetpack Compose で挑む新聞紙面UI ─ 複合ジェスチャー・ポリゴン記事領域・適応的ページ構成という3つの壁/droidkaigi2026
nikkei_engineer_recruiting
0
200
enechainの内製セルフサービスプラットフォーム
hiyosi
0
110
Kiro Crewしか勝たん!?
miu_crescent
PRO
0
180
Bet AI Day 2026丨AIによって本質に戻るシステムリスク管理
layerx
PRO
0
880
いま、生成AIにKaggleをどこまで 任せられるか — ROGIIコンペでの進め方とTips
k951286
3
1.4k
AndroidでHDRメディアを「壊さずに」扱う
chigichan24
0
400
AIに丸投げしないトイル削減 / Eliminating Toil Without Leaving It All to AI
kohbis
2
200
Featured
See All Featured
Color Theory Basics | Prateek | Gurzu
gurzu
0
460
SEO Brein meetup: CTRL+C is not how to scale international SEO
lindahogenes
1
2.9k
Building an army of robots
kneath
306
46k
Practical Orchestrator
shlominoach
191
12k
Fireside Chat
paigeccino
42
4k
Unlocking the hidden potential of vector embeddings in international SEO
frankvandijk
0
920
Bioeconomy Workshop: Dr. Julius Ecuru, Opportunities for a Bioeconomy in West Africa
akademiya2063
PRO
1
340
[SF Ruby Conf 2025] Rails X
palkan
2
1.3k
Navigating Weather and Climate Data
rabernat
0
510
Impact Scores and Hybrid Strategies: The future of link building
tamaranovitovic
0
430
Embracing the Ebb and Flow
colly
88
5.2k
Stewardship and Sustainability of Urban and Community Forests
pwiseman
0
510
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+)