SlideShare a Scribd company logo
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

PDF
Save time with kotlin in android development
PDF
Practical tips for building apps with kotlin
PDF
Kotlin for Android devs
PPTX
Say Goodbye To Java: Getting Started With Kotlin For Android Development
PPTX
Getting Started With Kotlin
PDF
eMan Dev Meetup: Kotlin For Android (part 03/03) 18.5.2017
PDF
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
PDF
Reactive Programming with JavaScript
Save time with kotlin in android development
Practical tips for building apps with kotlin
Kotlin for Android devs
Say Goodbye To Java: Getting Started With Kotlin For Android Development
Getting Started With Kotlin
eMan Dev Meetup: Kotlin For Android (part 03/03) 18.5.2017
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
Reactive Programming with JavaScript

What's hot (20)

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

Similar to Android Architecture Components with Kotlin (20)

PDF
Building Modern Apps using Android Architecture Components
PDF
Architecture Components
PDF
Android Jetpack - Google IO Extended Singapore 2018
PDF
Android Architecture Components
PDF
Architecture components - IT Talk
PDF
Architecture Components
PPTX
Android architectural components
PPTX
How Android Architecture Components can Help You Improve Your App’s Design?
PPTX
Android Architecture Components
PPTX
Android Architecture - Khoa Tran
PPTX
Architecture components, Константин Марс, TeamLead, Senior Developer, DataArt
PDF
Android Architecture Components
PPTX
Model viewviewmodel2
PPTX
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
PDF
Cleaning your architecture with android architecture components
PPTX
Android Architecture Components - Guy Bar on, Vonage
PDF
Survive the lifecycle
PDF
Handling Lifecycles in a Jetpack way
PPTX
The Best Way to Become an Android Developer Expert with Android Jetpack
PPTX
Presentation Android Architecture Components
Building Modern Apps using Android Architecture Components
Architecture Components
Android Jetpack - Google IO Extended Singapore 2018
Android Architecture Components
Architecture components - IT Talk
Architecture Components
Android architectural components
How Android Architecture Components can Help You Improve Your App’s Design?
Android Architecture Components
Android Architecture - Khoa Tran
Architecture components, Константин Марс, TeamLead, Senior Developer, DataArt
Android Architecture Components
Model viewviewmodel2
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Cleaning your architecture with android architecture components
Android Architecture Components - Guy Bar on, Vonage
Survive the lifecycle
Handling Lifecycles in a Jetpack way
The Best Way to Become an Android Developer Expert with Android Jetpack
Presentation Android Architecture Components
Ad

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
MYSQL Presentation for SQL database connectivity
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Cloud computing and distributed systems.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Modernizing your data center with Dell and AMD
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
cuic standard and advanced reporting.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
MYSQL Presentation for SQL database connectivity
“AI and Expert System Decision Support & Business Intelligence Systems”
NewMind AI Weekly Chronicles - August'25 Week I
Dropbox Q2 2025 Financial Results & Investor Presentation
Chapter 2 Digital Image Fundamentals.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Diabetes mellitus diagnosis method based random forest with bat algorithm
Big Data Technologies - Introduction.pptx
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Advanced Soft Computing BINUS July 2025.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Reach Out and Touch Someone: Haptics and Empathic Computing
Cloud computing and distributed systems.
Per capita expenditure prediction using model stacking based on satellite ima...
Modernizing your data center with Dell and AMD
Review of recent advances in non-invasive hemoglobin estimation
20250228 LYD VKU AI Blended-Learning.pptx
cuic standard and advanced reporting.pdf
Understanding_Digital_Forensics_Presentation.pptx

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