SlideShare a Scribd company logo
1 of 55
Download to read offline
Kotlin and Android Arch
Components
Adit Lal
@aditlal
Introduction
An application with a solid architecture should be:
•Easy to scale and maintain.
•Each component should be isolated and
decoupled.
•Easy to test
Kotlin and Android Arch Components
Kotlin and Android Arch Components
Components
Create an UI that
automatically
responds to
lifecycle events.
Lifecycle
Kotlin and Android Arch Components
Components
Create an UI that
automatically
responds to
lifecycle events.
Lifecycle LiveData
Build data objects
that notify views
when underlying
data changes
Kotlin and Android Arch Components
Components
Create an UI that
automatically
responds to
lifecycle events.
Lifecycle LiveData ViewModel
Build data objects
that notify views
when underlying
data changes
Store UI related
data that isn’t
destroyed on app
rotation
Kotlin and Android Arch Components
Components
Create an UI that
automatically
responds to
lifecycle events.
Lifecycle LiveData ViewModel Room
Build data objects
that notify views
when underlying
data changes
Store UI related
data that isn’t
destroyed on app
rotation
Access your data
with the power of
SQLite and safety
of in-app objects.
Kotlin and Android Arch Components
Lifecycle
States and Events
Kotlin and Android Arch Components
Kotlin and Android Arch Components
Lifecycle
Kotlin and Android Arch Components
Lifecycle
Kotlin and Android Arch Components
Kotlin and Android Arch Components
/**
* Displays a message when app comes to foreground and goes to background.
*/
class AppLifecycleObserver @Inject constructor(context: Context) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onEnterForeground() {
enterForegroundToast.showAfterCanceling(enterBackgroundToast)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onEnterBackground() {
enterBackgroundToast.showAfterCanceling(enterForegroundToast)
}
}
Lifecycle
Kotlin and Android Arch Components
class AppLifecycleObserver @Inject constructor(context: Context) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onEnterForeground() {
enterForegroundToast.showAfterCanceling(enterBackgroundToast)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onEnterBackground() {
enterBackgroundToast.showAfterCanceling(enterForegroundToast)
}
}
Lifecycle
ProcessLifecycleOwner.get().lifecycle.addObserver(appLifecycleObserver)
Kotlin and Android Arch Components
/**
* Displays a message when app comes to foreground and goes to background.
*/
class AppLifecycleObserver @Inject constructor(context: Context) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onEnterForeground() {
enterForegroundToast.showAfterCanceling(enterBackgroundToast)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onEnterBackground() {
enterBackgroundToast.showAfterCanceling(enterForegroundToast)
}
}
Lifecycle
Kotlin and Android Arch Components
/**
* Displays a message when app comes to foreground and goes to background.
*/
class AppLifecycleObserver @Inject constructor(context: Context) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onEnterForeground() {
enterForegroundToast.showAfterCanceling(enterBackgroundToast)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onEnterBackground() {
enterBackgroundToast.showAfterCanceling(enterForegroundToast)
}
}
Lifecycle
LiveData
LiveData is an observable data holder. It lets the
components in your app, usually the UI, observe
data objects for changes.
Kotlin and Android Arch Components
Kotlin and Android Arch Components
LiveData
Kotlin and Android Arch Components
LiveData
Kotlin and Android Arch Components
LiveData
LiveData
var userLiveData : MutableLiveData<List<User>> =
MutableLiveData();
LiveData
var userLiveData : MutableLiveData<List<User>> =
MutableLiveData();
userLiveData.value = User(id=1, name="John Doe”)
LiveData
var userLiveData : MutableLiveData<List<User>> =
MutableLiveData();
userLiveData.value = User(id=1, name="John Doe”)
//Activity or fragment
viewModel.getUsers().observe(
this,
Observer { result ->
run {
//Handle Result
}
})
LiveData
ViewModel
Observes the lifecycle state of the view,
maintaining consistency during configuration
changes and other Android lifecycle events.
The ViewModel class is designed to store and
manage UI-related data so that the data survives
configuration changes such as screen rotations. 
Kotlin and Android Arch Components
ViewModel
ViewModel
class NoteViewModel
@Inject constructor(var repo: NotesRepository) : ViewModel() {
fun getNotes(sort: String): LiveData<List<Note>> {
return repo.getAllNotes(sort = sort)
}
fun addNote(note: Note): LiveData<Note> {
return repo.addNote(note = note)
}
fun deleteNote(note: Note): LiveData<Int> {
return repo.deleteNote(note)
}
ViewModel
class NoteViewModel
@Inject constructor(var repo: NotesRepository) : ViewModel() {
fun getNotes(sort: String): LiveData<List<Note>> {
return repo.getAllNotes(sort = sort)
}
fun addNote(note: Note): LiveData<Note> {
return repo.addNote(note = note)
}
fun deleteNote(note: Note): LiveData<Int> {
return repo.deleteNote(note)
}
ViewModel
class NoteViewModel
@Inject constructor(var repo: NotesRepository) : ViewModel() {
fun getNotes(sort: String): LiveData<List<Note>> {
return repo.getAllNotes(sort = sort)
}
fun addNote(note: Note): LiveData<Note> {
return repo.addNote(note = note)
}
fun deleteNote(note: Note): LiveData<Int> {
return repo.deleteNote(note)
}
ViewModel
class NotesListActivity : AppCompatActivity(){
private lateinit var notesList: ArrayList<Note>
@Inject lateinit var viewModelFactory: ViewModelFactory
private val viewModel by lazy {
ViewModelProviders.of(
this@NotesListActivity,
viewModelFactory).get(NoteViewModel::class.java)
}
...
}
ViewModel
ViewModel
@Inject lateinit var viewModelFactory: ViewModelFactory
private val viewModel by lazy { ViewModelProviders.of(this@NotesListActivity,
viewModelFactory).get(NoteViewModel::class.java)
}
//Activity
viewModel.getNotes(sort = sort).observe(
this,
Observer { data ->
run {
notesList.clear()
notesList.addAll(data!!)
adapter.updateItems(notesList)
}
})
ViewModel
Room
Persistence library for Android
Kotlin and Android Arch Components
Entities and Dao’s
Kotlin and Android Arch Components
Room
@Entity(tableName = "user_table")
data class User(var created: Date = Date(),
var name: String = "",
@PrimaryKey var id: Int = 0)
Entities
interface BaseDao<T> {
@Insert
fun insert(vararg obj: T)
}
@Dao
abstract class DataDao : BaseDao<Data>() {
@Query("SELECT * FROM Data")
abstract fun getData(): List<Data>
}
Dao
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(user: User)
@Delete
fun delete(user: User)
@Query("SELECT * FROM user_table")
fun getUsers(): List<User>
}
Dao
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(user: User)
@Delete
fun delete(user: User)
@Query("SELECT * FROM user_table")
fun getUsers(): List<User>
}
Dao
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(user: User)
@Delete
fun delete(user: User)
@Query("SELECT * FROM user_table")
fun getUsers(): LiveData<List<User>>
}
Dao
@Transaction
open fun updateData(users: List<User>) {
deleteAllUsers()
insertAll(users)
}
Dao
class UserAndAllPets {
@Embedded
var user: User? = null
@Relation(parentColumn = “userId”,
entityColumn = “owner”)
var pets: List<Pet> = ArrayList()
}
//UserDao.kt
@Transaction
@Query(“SELECT * FROM Users”)
List<UserAndAllPets> getUsers();
Dao
@Database(entities = arrayOf(User::class),
version = 1,
exportSchema = true)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun UserDao(): UserDao
}
Database
class MyApp : Application() {
lateinit var mDataBase: AppDatabase
override fun onCreate() {
super.onCreate()
mDataBase = Room.databaseBuilder(this,
AppDatabase::class.java,
"users").build()
}
}
Database
@Provides
@Singleton
fun provideDB(context: Context): AppDatabase =
Room.databaseBuilder(context, AppDatabase::class.java, “users")
.fallbackToDestructiveMigration()
.build()
Database
Paging
Efficient Lists and data loading
Kotlin and Android Arch Components
Paging
Paging
class MyPagedListAdapter(diffCallback: DiffCallback<User>) :
PagedListAdapter<User, MyPagedListAdapter.ViewHolder>(diffCallback) {
PagedListAdapter
override fun onBindViewHolder(holder: MyPagedListAdapter.ViewHolder?, position: Int) {
getItem(position)?.let {
holder?.setData(it)
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int):
MyPagedListAdapter.ViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_user, parent, false)
return ViewHolder(view)
}
}
class MyPagedListAdapter(diffCallback: DiffCallback<User>) :
PagedListAdapter<User, MyPagedListAdapter.ViewHolder>(diffCallback) {
PagedListAdapter
override fun onBindViewHolder(holder: MyPagedListAdapter.ViewHolder?, position: Int) {
getItem(position)?.let {
holder?.setData(it)
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int):
MyPagedListAdapter.ViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_user, parent, false)
return ViewHolder(view)
}
}
class MyPagedListAdapter(diffCallback: DiffCallback<User>) :
PagedListAdapter<User, MyPagedListAdapter.ViewHolder>(diffCallback) {
PagedListAdapter
override fun onBindViewHolder(holder: MyPagedListAdapter.ViewHolder?, position: Int) {
getItem(position)?.let {
holder?.setData(it)
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int):
MyPagedListAdapter.ViewHolder {
val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_user, parent, false)
return ViewHolder(view)
}
}
DiffCallback
private val diffCallback = object : DiffUtil.ItemCallback<User>() {
override fun areItemsTheSame(oldItem: User, newItem: User): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: User, newItem: User): Boolean =
oldItem == newItem
}
}
Query
@Query("SELECT * FROM users ORDER WHERE age>:age ORDER by
name DESC, id ASC")
abstract fun usersOlderThan(age: Int): LivePagedListProvider<Int, User>
ViewModel
class UserViewModel(val db:AppDB) : ViewModel() {
val users: LiveData<PagedList<User>>
fun getUsersOlderThan(age) {
users = db.userDao().usersOlderThan(age)
.create(0, PagedList.Config.Builder()
.setPageSize(20)
.setPrefetchDistance(20)
.setEnablePlaceholders(false)
.build())
}
}
Activity
viewModel.getUsersOlderThan(5).observe(this, pagedList -> {
usersAdapter.setList(pagedList);
});
Thank you
Questions
Kotlin and Android Arch Components
@aditlal

More Related Content

What's hot

ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?intelliyole
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor ExtensionsConnect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensionsstable|kernel
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with AndroidKurt Renzo Acosta
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017Hardik Trivedi
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Kotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confFabio Collini
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Managementstable|kernel
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Andrey Breslav
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
Connect.Tech- Level Up Your Game With TravisCI
Connect.Tech- Level Up Your Game With TravisCIConnect.Tech- Level Up Your Game With TravisCI
Connect.Tech- Level Up Your Game With TravisCIstable|kernel
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Arnaud Giuliani
 

What's hot (20)

ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor ExtensionsConnect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Kotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community conf
 
Connect.Tech- Swift Memory Management
Connect.Tech- Swift Memory ManagementConnect.Tech- Swift Memory Management
Connect.Tech- Swift Memory Management
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011Kotlin Slides from Devoxx 2011
Kotlin Slides from Devoxx 2011
 
Kotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekito
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Connect.Tech- Level Up Your Game With TravisCI
Connect.Tech- Level Up Your Game With TravisCIConnect.Tech- Level Up Your Game With TravisCI
Connect.Tech- Level Up Your Game With TravisCI
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
 

Similar to Android Architecture Components with Kotlin

Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsHassan Abid
 
Android Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageAndroid Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageDroidConTLV
 
Unity and Azure Mobile Services using Prime31 plugin
Unity and Azure Mobile Services using Prime31 pluginUnity and Azure Mobile Services using Prime31 plugin
Unity and Azure Mobile Services using Prime31 pluginDavid Douglas
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT TalkConstantine Mars
 
Architecture Components
Architecture Components Architecture Components
Architecture Components DataArt
 
Architecture Components
Architecture ComponentsArchitecture Components
Architecture ComponentsSang Eel Kim
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android JetpackAhmad Arif Faizin
 
MobiConf 2018 | Room: an SQLite object mapping library
MobiConf 2018 | Room: an SQLite object mapping library MobiConf 2018 | Room: an SQLite object mapping library
MobiConf 2018 | Room: an SQLite object mapping library Magda Miu
 
Utilizando Espresso e UIAutomator no Teste de Apps Android
Utilizando Espresso e UIAutomator no Teste de Apps AndroidUtilizando Espresso e UIAutomator no Teste de Apps Android
Utilizando Espresso e UIAutomator no Teste de Apps AndroidEduardo Carrara de Araujo
 
Android apps development
Android apps developmentAndroid apps development
Android apps developmentMonir Zzaman
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)Giuseppe Filograno
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdfImranS18
 
Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...DroidConTLV
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recieversUtkarsh Mankad
 
Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)Fafadia Tech
 
Reactive clean architecture
Reactive clean architectureReactive clean architecture
Reactive clean architectureViktor Nyblom
 
How Android Architecture Components can Help You Improve Your App’s Design?
How Android Architecture Components can Help You Improve Your App’s Design?How Android Architecture Components can Help You Improve Your App’s Design?
How Android Architecture Components can Help You Improve Your App’s Design?Paul Cook
 

Similar to Android Architecture Components with Kotlin (20)

Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
Stmik bandung
Stmik bandungStmik bandung
Stmik bandung
 
Android Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageAndroid Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, Vonage
 
Unity and Azure Mobile Services using Prime31 plugin
Unity and Azure Mobile Services using Prime31 pluginUnity and Azure Mobile Services using Prime31 plugin
Unity and Azure Mobile Services using Prime31 plugin
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
Architecture Components
Architecture Components Architecture Components
Architecture Components
 
Architecture Components
Architecture ComponentsArchitecture Components
Architecture Components
 
The Best Way to Become an Android Developer Expert with Android Jetpack
The Best Way to Become an Android Developer Expert  with Android JetpackThe Best Way to Become an Android Developer Expert  with Android Jetpack
The Best Way to Become an Android Developer Expert with Android Jetpack
 
MobiConf 2018 | Room: an SQLite object mapping library
MobiConf 2018 | Room: an SQLite object mapping library MobiConf 2018 | Room: an SQLite object mapping library
MobiConf 2018 | Room: an SQLite object mapping library
 
Utilizando Espresso e UIAutomator no Teste de Apps Android
Utilizando Espresso e UIAutomator no Teste de Apps AndroidUtilizando Espresso e UIAutomator no Teste de Apps Android
Utilizando Espresso e UIAutomator no Teste de Apps Android
 
Android apps development
Android apps developmentAndroid apps development
Android apps development
 
How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)How to become an Android dev starting from iOS (and vice versa)
How to become an Android dev starting from iOS (and vice versa)
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
 
Model viewviewmodel2
Model viewviewmodel2Model viewviewmodel2
Model viewviewmodel2
 
07_UIAndroid.pdf
07_UIAndroid.pdf07_UIAndroid.pdf
07_UIAndroid.pdf
 
Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...Android architecture components - how they fit in good old architectural patt...
Android architecture components - how they fit in good old architectural patt...
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)Introduction To Google Android (Ft Rohan Bomle)
Introduction To Google Android (Ft Rohan Bomle)
 
Reactive clean architecture
Reactive clean architectureReactive clean architecture
Reactive clean architecture
 
How Android Architecture Components can Help You Improve Your App’s Design?
How Android Architecture Components can Help You Improve Your App’s Design?How Android Architecture Components can Help You Improve Your App’s Design?
How Android Architecture Components can Help You Improve Your App’s Design?
 

Recently uploaded

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 

Recently uploaded (20)

TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 

Android Architecture Components with Kotlin

  • 1. Kotlin and Android Arch Components Adit Lal @aditlal
  • 2. Introduction An application with a solid architecture should be: •Easy to scale and maintain. •Each component should be isolated and decoupled. •Easy to test Kotlin and Android Arch Components
  • 3. Kotlin and Android Arch Components
  • 4. Components Create an UI that automatically responds to lifecycle events. Lifecycle Kotlin and Android Arch Components
  • 5. Components Create an UI that automatically responds to lifecycle events. Lifecycle LiveData Build data objects that notify views when underlying data changes Kotlin and Android Arch Components
  • 6. Components Create an UI that automatically responds to lifecycle events. Lifecycle LiveData ViewModel Build data objects that notify views when underlying data changes Store UI related data that isn’t destroyed on app rotation Kotlin and Android Arch Components
  • 7. Components Create an UI that automatically responds to lifecycle events. Lifecycle LiveData ViewModel Room Build data objects that notify views when underlying data changes Store UI related data that isn’t destroyed on app rotation Access your data with the power of SQLite and safety of in-app objects. Kotlin and Android Arch Components
  • 8. Lifecycle States and Events Kotlin and Android Arch Components
  • 9. Kotlin and Android Arch Components Lifecycle
  • 10. Kotlin and Android Arch Components Lifecycle
  • 11. Kotlin and Android Arch Components
  • 12. Kotlin and Android Arch Components /** * Displays a message when app comes to foreground and goes to background. */ class AppLifecycleObserver @Inject constructor(context: Context) : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onEnterForeground() { enterForegroundToast.showAfterCanceling(enterBackgroundToast) } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onEnterBackground() { enterBackgroundToast.showAfterCanceling(enterForegroundToast) } } Lifecycle
  • 13. Kotlin and Android Arch Components class AppLifecycleObserver @Inject constructor(context: Context) : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onEnterForeground() { enterForegroundToast.showAfterCanceling(enterBackgroundToast) } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onEnterBackground() { enterBackgroundToast.showAfterCanceling(enterForegroundToast) } } Lifecycle ProcessLifecycleOwner.get().lifecycle.addObserver(appLifecycleObserver)
  • 14. Kotlin and Android Arch Components /** * Displays a message when app comes to foreground and goes to background. */ class AppLifecycleObserver @Inject constructor(context: Context) : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onEnterForeground() { enterForegroundToast.showAfterCanceling(enterBackgroundToast) } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onEnterBackground() { enterBackgroundToast.showAfterCanceling(enterForegroundToast) } } Lifecycle
  • 15. Kotlin and Android Arch Components /** * Displays a message when app comes to foreground and goes to background. */ class AppLifecycleObserver @Inject constructor(context: Context) : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onEnterForeground() { enterForegroundToast.showAfterCanceling(enterBackgroundToast) } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onEnterBackground() { enterBackgroundToast.showAfterCanceling(enterForegroundToast) } } Lifecycle
  • 16. LiveData LiveData is an observable data holder. It lets the components in your app, usually the UI, observe data objects for changes. Kotlin and Android Arch Components
  • 17. Kotlin and Android Arch Components LiveData
  • 18. Kotlin and Android Arch Components LiveData
  • 19. Kotlin and Android Arch Components LiveData
  • 20. LiveData var userLiveData : MutableLiveData<List<User>> = MutableLiveData();
  • 21. LiveData var userLiveData : MutableLiveData<List<User>> = MutableLiveData(); userLiveData.value = User(id=1, name="John Doe”)
  • 22. LiveData var userLiveData : MutableLiveData<List<User>> = MutableLiveData(); userLiveData.value = User(id=1, name="John Doe”) //Activity or fragment viewModel.getUsers().observe( this, Observer { result -> run { //Handle Result } })
  • 24. ViewModel Observes the lifecycle state of the view, maintaining consistency during configuration changes and other Android lifecycle events. The ViewModel class is designed to store and manage UI-related data so that the data survives configuration changes such as screen rotations.  Kotlin and Android Arch Components
  • 27. class NoteViewModel @Inject constructor(var repo: NotesRepository) : ViewModel() { fun getNotes(sort: String): LiveData<List<Note>> { return repo.getAllNotes(sort = sort) } fun addNote(note: Note): LiveData<Note> { return repo.addNote(note = note) } fun deleteNote(note: Note): LiveData<Int> { return repo.deleteNote(note) } ViewModel
  • 28. class NoteViewModel @Inject constructor(var repo: NotesRepository) : ViewModel() { fun getNotes(sort: String): LiveData<List<Note>> { return repo.getAllNotes(sort = sort) } fun addNote(note: Note): LiveData<Note> { return repo.addNote(note = note) } fun deleteNote(note: Note): LiveData<Int> { return repo.deleteNote(note) } ViewModel
  • 29. class NoteViewModel @Inject constructor(var repo: NotesRepository) : ViewModel() { fun getNotes(sort: String): LiveData<List<Note>> { return repo.getAllNotes(sort = sort) } fun addNote(note: Note): LiveData<Note> { return repo.addNote(note = note) } fun deleteNote(note: Note): LiveData<Int> { return repo.deleteNote(note) } ViewModel
  • 30. class NotesListActivity : AppCompatActivity(){ private lateinit var notesList: ArrayList<Note> @Inject lateinit var viewModelFactory: ViewModelFactory private val viewModel by lazy { ViewModelProviders.of( this@NotesListActivity, viewModelFactory).get(NoteViewModel::class.java) } ... } ViewModel
  • 32. @Inject lateinit var viewModelFactory: ViewModelFactory private val viewModel by lazy { ViewModelProviders.of(this@NotesListActivity, viewModelFactory).get(NoteViewModel::class.java) } //Activity viewModel.getNotes(sort = sort).observe( this, Observer { data -> run { notesList.clear() notesList.addAll(data!!) adapter.updateItems(notesList) } }) ViewModel
  • 33. Room Persistence library for Android Kotlin and Android Arch Components
  • 34. Entities and Dao’s Kotlin and Android Arch Components Room
  • 35. @Entity(tableName = "user_table") data class User(var created: Date = Date(), var name: String = "", @PrimaryKey var id: Int = 0) Entities
  • 36. interface BaseDao<T> { @Insert fun insert(vararg obj: T) } @Dao abstract class DataDao : BaseDao<Data>() { @Query("SELECT * FROM Data") abstract fun getData(): List<Data> } Dao
  • 37. @Dao interface UserDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(user: User) @Delete fun delete(user: User) @Query("SELECT * FROM user_table") fun getUsers(): List<User> } Dao
  • 38. @Dao interface UserDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(user: User) @Delete fun delete(user: User) @Query("SELECT * FROM user_table") fun getUsers(): List<User> } Dao
  • 39. @Dao interface UserDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(user: User) @Delete fun delete(user: User) @Query("SELECT * FROM user_table") fun getUsers(): LiveData<List<User>> } Dao
  • 40. @Transaction open fun updateData(users: List<User>) { deleteAllUsers() insertAll(users) } Dao
  • 41. class UserAndAllPets { @Embedded var user: User? = null @Relation(parentColumn = “userId”, entityColumn = “owner”) var pets: List<Pet> = ArrayList() } //UserDao.kt @Transaction @Query(“SELECT * FROM Users”) List<UserAndAllPets> getUsers(); Dao
  • 42. @Database(entities = arrayOf(User::class), version = 1, exportSchema = true) @TypeConverters(Converters::class) abstract class AppDatabase : RoomDatabase() { abstract fun UserDao(): UserDao } Database
  • 43. class MyApp : Application() { lateinit var mDataBase: AppDatabase override fun onCreate() { super.onCreate() mDataBase = Room.databaseBuilder(this, AppDatabase::class.java, "users").build() } } Database
  • 44. @Provides @Singleton fun provideDB(context: Context): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, “users") .fallbackToDestructiveMigration() .build() Database
  • 45. Paging Efficient Lists and data loading Kotlin and Android Arch Components
  • 48. class MyPagedListAdapter(diffCallback: DiffCallback<User>) : PagedListAdapter<User, MyPagedListAdapter.ViewHolder>(diffCallback) { PagedListAdapter override fun onBindViewHolder(holder: MyPagedListAdapter.ViewHolder?, position: Int) { getItem(position)?.let { holder?.setData(it) } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyPagedListAdapter.ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_user, parent, false) return ViewHolder(view) } }
  • 49. class MyPagedListAdapter(diffCallback: DiffCallback<User>) : PagedListAdapter<User, MyPagedListAdapter.ViewHolder>(diffCallback) { PagedListAdapter override fun onBindViewHolder(holder: MyPagedListAdapter.ViewHolder?, position: Int) { getItem(position)?.let { holder?.setData(it) } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyPagedListAdapter.ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_user, parent, false) return ViewHolder(view) } }
  • 50. class MyPagedListAdapter(diffCallback: DiffCallback<User>) : PagedListAdapter<User, MyPagedListAdapter.ViewHolder>(diffCallback) { PagedListAdapter override fun onBindViewHolder(holder: MyPagedListAdapter.ViewHolder?, position: Int) { getItem(position)?.let { holder?.setData(it) } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyPagedListAdapter.ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_user, parent, false) return ViewHolder(view) } }
  • 51. DiffCallback private val diffCallback = object : DiffUtil.ItemCallback<User>() { override fun areItemsTheSame(oldItem: User, newItem: User): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: User, newItem: User): Boolean = oldItem == newItem } }
  • 52. Query @Query("SELECT * FROM users ORDER WHERE age>:age ORDER by name DESC, id ASC") abstract fun usersOlderThan(age: Int): LivePagedListProvider<Int, User>
  • 53. ViewModel class UserViewModel(val db:AppDB) : ViewModel() { val users: LiveData<PagedList<User>> fun getUsersOlderThan(age) { users = db.userDao().usersOlderThan(age) .create(0, PagedList.Config.Builder() .setPageSize(20) .setPrefetchDistance(20) .setEnablePlaceholders(false) .build()) } }
  • 55. Thank you Questions Kotlin and Android Arch Components @aditlal