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

What's hot (20)

PDF
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
ODP
From object oriented to functional domain modeling
Codemotion
 
PDF
Kotlin: Why Do You Care?
intelliyole
 
PDF
JavaScript in 2016
Codemotion
 
PDF
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
stable|kernel
 
PPTX
Building Mobile Apps with Android
Kurt Renzo Acosta
 
PDF
Kotlin intro
Elifarley Cruz
 
PDF
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
PPT
The Kotlin Programming Language
intelliyole
 
PDF
Kotlin Delegates in practice - Kotlin community conf
Fabio Collini
 
PDF
Connect.Tech- Swift Memory Management
stable|kernel
 
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
PDF
Swift and Kotlin Presentation
Andrzej Sitek
 
PDF
Kotlin Slides from Devoxx 2011
Andrey Breslav
 
PDF
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
PDF
Using hilt in a modularized project
Fabio Collini
 
PDF
Connect.Tech- Level Up Your Game With TravisCI
stable|kernel
 
PDF
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
PDF
Little Helpers for Android Development with Kotlin
Kai Koenig
 
PDF
Kotlin hands on - MorningTech ekito 2017
Arnaud Giuliani
 
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
From object oriented to functional domain modeling
Codemotion
 
Kotlin: Why Do You Care?
intelliyole
 
JavaScript in 2016
Codemotion
 
Connect.Tech- Enhancing Your Workflow With Xcode Source Editor Extensions
stable|kernel
 
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Kotlin intro
Elifarley Cruz
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
The Kotlin Programming Language
intelliyole
 
Kotlin Delegates in practice - Kotlin community conf
Fabio Collini
 
Connect.Tech- Swift Memory Management
stable|kernel
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
Swift and Kotlin Presentation
Andrzej Sitek
 
Kotlin Slides from Devoxx 2011
Andrey Breslav
 
Kotlin cheat sheet by ekito
Arnaud Giuliani
 
Using hilt in a modularized project
Fabio Collini
 
Connect.Tech- Level Up Your Game With TravisCI
stable|kernel
 
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Little Helpers for Android Development with Kotlin
Kai Koenig
 
Kotlin hands on - MorningTech ekito 2017
Arnaud Giuliani
 

Similar to Android Architecture Components with Kotlin (20)

PDF
Building Modern Apps using Android Architecture Components
Hassan Abid
 
PDF
Architecture Components
Sang Eel Kim
 
PDF
Android Jetpack - Google IO Extended Singapore 2018
Hassan Abid
 
PDF
Android Architecture Components
Gabriel Samojło
 
PDF
Architecture Components
DataArt
 
PDF
Architecture components - IT Talk
Constantine Mars
 
PPTX
Android architectural components
Muhammad Ali
 
PPTX
How Android Architecture Components can Help You Improve Your App’s Design?
Paul Cook
 
PPTX
Android Architecture Components
BurhanuddinRashid
 
PPTX
Android Architecture - Khoa Tran
Tu Le Dinh
 
PPTX
Architecture components, Константин Марс, TeamLead, Senior Developer, DataArt
Alina Vilk
 
PDF
Android Architecture Components
Darshan Parikh
 
PPTX
Model viewviewmodel2
Suraj Kulkarni
 
PPTX
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Waheed Nazir
 
PDF
Cleaning your architecture with android architecture components
Debora Gomez Bertoli
 
PPTX
Android Architecture Components - Guy Bar on, Vonage
DroidConTLV
 
PDF
Survive the lifecycle
Simon Joecks
 
PDF
Handling Lifecycles in a Jetpack way
Han Yin
 
PPTX
The Best Way to Become an Android Developer Expert with Android Jetpack
Ahmad Arif Faizin
 
PPTX
Presentation Android Architecture Components
Attract Group
 
Building Modern Apps using Android Architecture Components
Hassan Abid
 
Architecture Components
Sang Eel Kim
 
Android Jetpack - Google IO Extended Singapore 2018
Hassan Abid
 
Android Architecture Components
Gabriel Samojło
 
Architecture Components
DataArt
 
Architecture components - IT Talk
Constantine Mars
 
Android architectural components
Muhammad Ali
 
How Android Architecture Components can Help You Improve Your App’s Design?
Paul Cook
 
Android Architecture Components
BurhanuddinRashid
 
Android Architecture - Khoa Tran
Tu Le Dinh
 
Architecture components, Константин Марс, TeamLead, Senior Developer, DataArt
Alina Vilk
 
Android Architecture Components
Darshan Parikh
 
Model viewviewmodel2
Suraj Kulkarni
 
Android MVVM architecture using Kotlin, Dagger2, LiveData, MediatorLiveData
Waheed Nazir
 
Cleaning your architecture with android architecture components
Debora Gomez Bertoli
 
Android Architecture Components - Guy Bar on, Vonage
DroidConTLV
 
Survive the lifecycle
Simon Joecks
 
Handling Lifecycles in a Jetpack way
Han Yin
 
The Best Way to Become an Android Developer Expert with Android Jetpack
Ahmad Arif Faizin
 
Presentation Android Architecture Components
Attract Group
 
Ad

Recently uploaded (20)

PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Ad

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