SlideShare a Scribd company logo
Exploring Kotlin
Atiq Ur Rehman
@TheMaxCoder
Atiq Ur Rehman - Freelance Android Developer
Introduction to Kotlin
What is Kotlin
- General-purpose
- OOP + FP
- Static typing
- Open source (Apache 2.0)
- Developed by JetBrains
Kotlin Philosophy
- Concise
- Safe
- Interoperable
- Tool-friendly
Timeline
2010 Project started
2016 Kotlin 1.0
2017 Official on Android
2018 Kotlin 1.3
Current adoption
Build Applications For
Kotlin/JVM
- Supports JVM 1.6+
- 100% Java Interop
- You can use all the existing Java frameworks & libraries
- Automatic Java to Kotlin conversion
Kotlin/Android
- Officially Supported
- Android KTX
Kotlin/JS
- Transpile to JavaScript
- Readable generated JS code
- JS interop
Kotlin/Native
- Targets
- iOS / Android
- Windows, Linux, Mac
- Small Devices
- C, Swift, Objective-C
Multiplatform projects
Some Kotlin Features
Extension functions
fun Date.isSaturday(): Boolean {
return day == 6
}
val today = Date(2019, 6, 22)
if(today.isSaturday()) {
println("Today is a Saturday")
} else {
println("Today is not a Saturday")
}
fun Date.isSaturday(): Boolean {
return day == 6
}
Higher-Order Functions
fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this){
action(element)
}
}
Higher-Order Functions
fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
Higher-Order Functions
fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
Higher-Order Functions
fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this){
action(element)
}
}
Higher-Order Functions
fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this){
action(element)
}
}
// Usage
list.forEach { print(it) }
Named Arguments
fun requestLogin(name: String, pass: String)
Named Arguments
requestLogin(name = “Atiq”, pass = “kotlin”)
Named Arguments
requestLogin(pass = “kotlin”, name = “Atiq”)
Named Arguments
fun requestLogin(name: String = “Atiq”, pass: String)
Named Arguments
requestLogin(pass = “Kotlin”)
Using Kotlin Coroutines
in your Android App
Long running tasks
● Network requests
● Database operations
● Image processing
● ...
Challenge 1: Execute on a non-UI thread
Challenge 1: Execute on a non-UI thread
Challenge 2: Get informed when the task is done
Challenge 1: Execute on a non-UI thread
Challenge 2: Get informed when the task is done
Android solutions
● AsyncTask
● Loaders (deprecated in Android P)
● RxJava
● Thread / HandlerThread / Executor with callbacks
Threads and callbacks
fun login(name, pass) {
val thread = Thread(Runnable() -> {
requestLogin(name, pass) { result ->
show(result)
}
}
thread.start()
}
Threads and callbacks
fun login(name, pass) {
val thread = Thread(Runnable() -> {
requestLogin(name, pass) { result ->
Handler(Looper.getMainLooper()) {
show(result)
}
}
Threads and callbacks
fun login(name, pass) {
requestLogin(name, pass) { result -> show(result) }
}
UI Thread
fun login(name, pass) {
requestLogin(name, pass) { result -> show(result) }
}
UI Thread
fun login(name, pass) {
requestLogin(name, pass) { result -> show(result) }
}
UI Thread
fun login(name, pass) {
requestLogin(name, pass) { result -> show(result) }
}
Coroutine
= suspendable computation
UI Thread
https://medium.com/@elye.project/understanding-suspend-function-of-coroutines-de26b070c5ed
https://medium.com/@elye.project/understanding-suspend-function-of-coroutines-de26b070c5ed
Coroutine
Write asynchronous code sequentially
fun login(name, pass) = launch {
val result = requestLogin(name, pass)
show(result)
}
Coroutine
~ lightweight thread
fun login(name, pass) = launch {
val result = requestLogin(name, pass)
show(result)
}
fun login(name, pass) = launch(Dispatchers.IO){
val result = requestLogin(name, pass)
withContext(Dispatchers.Main) {
show(result)
}
}
Coroutine
● Not bound to a specific thread
● Complete with a result
fun login(name, pass) {
requestLogin(name, pass) { result -> show(result) }
}
Thread
suspend fun requestLogin(
name: String, pass: String
): Result {...}
suspend fun requestLogin(
name: String, pass: String
): Result {...}
Suspending functions do not block the caller thread.
suspend fun requestLogin(
name: String, pass: String
): Result = withContext(Dispatchers.IO) {
...
}
Dispatchers.Main
● Main thread
● Use it for: UI operations
Dispatchers.Default
● Common pool of shared background threads
● Use it for: computing-intensive coroutines
Dispatchers.Main
● Main thread
● Use it for: UI operations
Dispatchers.Default
● Common pool of shared background threads
● Use it for: computing-intensive coroutines
Dispatchers.IO
● Shared pool of on-demand created threads
● Use it for: IO-intensive blocking operations
Dispatchers.Main
● Main thread
● Use it for: UI operations
Dispatchers.Default
● Common pool of shared background threads
● Use it for: computing-intensive coroutines
Dispatchers.Unconfined
● Doesn’t confine the coroutine to any specific thread
● Don’t use it in code
Dispatchers.IO
● Shared pool of on-demand created threads
● Use it for: IO-intensive blocking operations
Dispatchers.Main
● Main thread
● Use it for: UI operations
suspend fun requestLogin(
name: String, pass: String
): Result = withContext(Dispatchers.IO) {
...
}
suspend fun login(name, pass) {
val result = requestLogin(name, pass)
show(result)
}
suspend fun requestLogin(
name: String, pass: String
): Result = withContext(Dispatchers.IO) {
...
}
suspend fun login(name, pass) {
val authToken = authenticate()
val result = requestLogin(authToken, name, pass)
show(result)
}
Sequential
suspend fun login(name, pass) {
val authToken = authenticate()
val result = requestLogin(authToken, name, pass)
show(result)
}
Data dependencies
suspend fun login(name, pass) {
try {
val result = requestLogin(name, pass)
show(result)
} catch (error: NetworkError){
}
}
Errors
Launching and cancelling coroutines
val job = Job()
val uiScope = CoroutineScope(Dispatchers.Main + job)
val job = Job()
val uiScope = CoroutineScope(Dispatchers.Main + job)
fun login(username: String, pass: String
) = uiScope.launch {
val result = requestLogin(name, pass)
show(result)
}
val job = Job()
val uiScope = CoroutineScope(Dispatchers.Main + job)
fun login(username: String, pass: String
) = uiScope.launch(Dispatchers.IO) {
val result = requestLogin(name, pass)
show(result)
}
val job = Job()
val uiScope = CoroutineScope(Dispatchers.Main + job)
fun login(
username: String, pass: String
) = uiScope.launch {
val result = requestLogin(name, pass)
show(result)
}
job.cancel()
Launching and cancelling coroutines
Launching and cancelling coroutines
fun onCleared() {
super.onCleared()
job.cancel()
}
class MyViewModel: ViewModel() {
val viewModelJob = Job()
val uiScope = CoroutineScope(Dispatchers.Main+viewModelJob)
fun login(
username: String, pass: String
) = uiScope.launch(Dispatchers.IO) {
val result = requestLogin(name, pass)
show(result)
}
fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
}
class MyViewModel: ViewModel() {
val viewModelJob = Job()
val uiScope = CoroutineScope(Dispatchers.Main+viewModelJob)
fun login(
username: String, pass: String
) = uiScope.launch(Dispatchers.IO) {
val result = requestLogin(name, pass)
show(result)
}
fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
}
lifecycle-viewmodel-ktx
class MyViewModel: ViewModel() {
fun login(
username: String, pass: String
) = viewModelScope.launch(Dispatchers.IO) {
val result = requestLogin(name, pass)
show(result)
}
}
● Coroutines
● suspend functions
● Dispatchers
● Launching a coroutine
● Using a coroutine from ViewModels
Useful Links
kotlinlang.org
try.kotlinlang.org and Kotlin Koans
Slack: slack.kotl.in
Thank You!
Slack Community of 150+ Pakistani Android Developers from all over the world
http://bit.ly/androiddevs-pakistan
TheMaxCoderr
facebook.com/TheMaxCoder

More Related Content

What's hot (20)

PDF
Bytecode manipulation with Javassist and ASM
ashleypuls
 
PDF
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
PPTX
K is for Kotlin
TechMagic
 
PDF
JUnit5 and TestContainers
Sunghyouk Bae
 
PDF
Java 7 New Features
Jussi Pohjolainen
 
PPT
JDK1.6
india_mani
 
PDF
Java7 New Features and Code Examples
Naresh Chintalcheru
 
PPTX
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
PPTX
Java7 - Top 10 Features
Andreas Enbohm
 
PPT
Scala
Andreas Enbohm
 
PDF
Utilizing Powerful Extensions for Analytics and Operations
Neo4j
 
PPTX
Hybrid Applications
Andreas Enbohm
 
PDF
Swift and Kotlin Presentation
Andrzej Sitek
 
PDF
The Future of Futures - A Talk About Java 8 CompletableFutures
Haim Yadid
 
PPTX
Kotlin is charming; The reasons Java engineers should start Kotlin.
JustSystems Corporation
 
PPT
55 New Features in Java 7
Boulder Java User's Group
 
PDF
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
PDF
Clojure for Java developers
John Stevenson
 
PDF
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
PDF
Introduction to kotlin
NAVER Engineering
 
Bytecode manipulation with Javassist and ASM
ashleypuls
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
K is for Kotlin
TechMagic
 
JUnit5 and TestContainers
Sunghyouk Bae
 
Java 7 New Features
Jussi Pohjolainen
 
JDK1.6
india_mani
 
Java7 New Features and Code Examples
Naresh Chintalcheru
 
The Road To Reactive with RxJava JEEConf 2016
Frank Lyaruu
 
Java7 - Top 10 Features
Andreas Enbohm
 
Utilizing Powerful Extensions for Analytics and Operations
Neo4j
 
Hybrid Applications
Andreas Enbohm
 
Swift and Kotlin Presentation
Andrzej Sitek
 
The Future of Futures - A Talk About Java 8 CompletableFutures
Haim Yadid
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
JustSystems Corporation
 
55 New Features in Java 7
Boulder Java User's Group
 
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Clojure for Java developers
John Stevenson
 
Alternatives of JPA/Hibernate
Sunghyouk Bae
 
Introduction to kotlin
NAVER Engineering
 

Similar to Exploring Kotlin (20)

PDF
Kotlin for Android Development
Speck&Tech
 
PPT
Laurens Van Den Oever Xopus Presentation
Ajax Experience 2009
 
PPT
Groovy & Grails: Scripting for Modern Web Applications
rohitnayak
 
ODP
Lambda Chops - Recipes for Simpler, More Expressive Code
Ian Robertson
 
PPTX
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
PPTX
Introduction to Vert.x
Yiguang Hu
 
PPT
JS everywhere 2011
Oleg Podsechin
 
PDF
Having Fun with Kotlin Android - DILo Surabaya
DILo Surabaya
 
ODP
Java Concurrency
Carol McDonald
 
PDF
Presto anatomy
Dongmin Yu
 
PPTX
XML-Free Programming
Stephen Chin
 
PDF
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
PPTX
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
PPTX
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
PDF
[245] presto 내부구조 파헤치기
NAVER D2
 
PPTX
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
PDF
Rapid Web API development with Kotlin and Ktor
Trayan Iliev
 
PDF
Nodejs and WebSockets
Gonzalo Ayuso
 
PDF
Groovy - Grails as a modern scripting language for Web applications
IndicThreads
 
PDF
Introduction to clojure
Abbas Raza
 
Kotlin for Android Development
Speck&Tech
 
Laurens Van Den Oever Xopus Presentation
Ajax Experience 2009
 
Groovy & Grails: Scripting for Modern Web Applications
rohitnayak
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Ian Robertson
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Introduction to Vert.x
Yiguang Hu
 
JS everywhere 2011
Oleg Podsechin
 
Having Fun with Kotlin Android - DILo Surabaya
DILo Surabaya
 
Java Concurrency
Carol McDonald
 
Presto anatomy
Dongmin Yu
 
XML-Free Programming
Stephen Chin
 
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
Kotlin Coroutines and Rx
Shaul Rosenzwieg
 
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
[245] presto 내부구조 파헤치기
NAVER D2
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Rapid Web API development with Kotlin and Ktor
Trayan Iliev
 
Nodejs and WebSockets
Gonzalo Ayuso
 
Groovy - Grails as a modern scripting language for Web applications
IndicThreads
 
Introduction to clojure
Abbas Raza
 
Ad

Recently uploaded (20)

PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Ad

Exploring Kotlin

Editor's Notes

  • #5: Kotlin is a general-purpose language that supports both functional programming and object-oriented programming paradigms. It’s an open-source project developed mainly by JetBrains with the help of the community. Like Java, Kotlin is a statically typed language, however, in Kotlin you can omit the types, and it often looks as concise as some other dynamically-typed languages.
  • #6: Kotlin is safe in a sense that Kotlin compiler helps to prevent a lot of possible types of errors. Kotlin has really good interoperability with Java, and rich tooling support.
  • #7: The project started at 2010. In 2017 it was acknowledged by Google as a first-class citizen on Android.
  • #8: Kotlin usage and Kotlin community is growing very fast.
  • #9: One can compile Kotlin code for different platforms, including JVM, Android, JavaScript and Native.
  • #10: Kotlin compiles to JVM bytecode starting from 1.6, so you can use it even for older versions of JVM without upgrading it. Thanks to Kotlin and Java interop, you can easily mix Kotlin and Java sources. You don’t have to convert all the existing code into Kotlin, you can slowly add new functionality written in Kotlin into existing Java project. IntelliJ IDEA and Android studio automatically convert Java code into Kotlin code with the copy-paste. That might be used for learning purposes or to provide smooth migration.
  • #11: Kotlin is an official language for Android, and a lot of Android specific documentation now targets Kotlin. Check out the Android KTX project which contains lots of helpful extensions for Kotlin.
  • #12: With Kotlin you can target JavaScript too. The compiler generates readable JS code from your Kotlin code. Note that converting Kotlin code to JavaScript code is called “transpiling”, not “compiling”. You can use the dynamic type to access any JS library without strong typing. To access third-party frameworks with a strongly-typed API, you can convert TypeScript definitions from the ”Definitely Typed” type definitions repository to Kotlin using the ts2kt tool.
  • #13: There are platforms, where virtual machine is not needed, banned or too heavy. Kotlin/Native is a good choice to jump into the world of native code. It uses LLVM backend and targets many native platforms. In addition to it, it adds an interop level with C and Objective-C libraries. You can use it to compile parts of your app for iOS.
  • #14: You can share the code written for different platforms by using Kotlin Multiplatform.
  • #15: Now we will talk about some of Kotlin’s coolest features, I have tried to keep them beginner friendly.
  • #18: Kotlin functions are first-class, which means that they can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions.
  • #19: Collection types, such as Iterable, Collection, List, Set, Map
  • #20: This is lambda expression that is saved in the argument
  • #21: Stld contains tons of such funtions
  • #22: Kotlin functions are first-class, which means that they can be stored in variables and data structures, passed as arguments to and returned from other higher-order functions.
  • #29: As Android developers, we have all sorts of long running tasks we need to execute: from network requests, to database operations or processing an image. But, in general, doing long running tasks comes with several challenges
  • #30: First, we want to make sure that all of these tasks are executed on a non-UI thread. We know that we have 16ms to draw the UI and anything taking more than those 16ms, will lead to jank So some of the APIs we use, force us to long running tasks on a background thread: the network stack throws NetworkOnMainThreadException Room throws java.lang.IllegalStateException: Cannot access database on the main thread So executing long running operations on a non-UI thread is a must in Android
  • #31: Next challenge is knowing when such a task is done. Completing a long running task often leads to some consequences - we’re saving the network response to the database, we’re informing the user of the success or failure of the operation. So, no matter what happens, we want to work with the result of the task.
  • #32: In Android we can approach these challenges with several APIs: We can use an AsyncTask, but then, you have to make sure you’re not connecting it to the lifecycle of an Activity and create memory leaks on Activity rotation and that you cancel the task when needed. We can use Loaders, but then this API was deprecated in Android P in favor of LiveData and ViewModels. But even with LiveData, we still need a way to run tasks on a background thread. You can use RxJava but keep in mind that RxJava brings with it a powerful streams API and you shouldn’t be using it just to switch threads. So, we could just handle our threading by directly using APIs like Thread, HandlerThread or Executor but the problem is that all of these APIs would need to be used with callbacks. The role of the callback would be to provide an action to be taken once the task is performed
  • #33: When working with callbacks it’s easy to get in a callback hell, decreasing the readability of the code.
  • #34: And, guess what, that show needs to be on the UI so we need to get a reference to the main looper
  • #35: If we’re not creating a new thread for our login request, the code looks something like this:
  • #36: But if we’re running this on the UI thread but We’re blocking the thread
  • #37: Only after the login is returned, we can unblock our thread and draw the UI again
  • #38: What we want is to let the thread do other things while waiting for the completion of a task, so more precisely, we want to suspend the thread at certain points. To achieve this, we will be working with coroutines.
  • #39: That’s what a coroutine is - an instance of a suspendable computation.
  • #40: Function A has to be completed before Function B continue. The thread is locked for Function A to complete it’s execution.
  • #41: Function A, while has started, could be suspended, and let Function B execute, then only resume later. The thread is not locked by Function A.
  • #42: Coroutines allow us to write async code sequentially
  • #43: Often, they tend to be compared to lightweight threads because just like with threads, it takes a block of code to run, it’s created and it’s started.
  • #44: But the difference appears in the fact that they’re not bound to a specific thread, it’s easy to switch threads and they complete with a result
  • #45: The points in the code where we want to suspend the execution, are called suspension points
  • #46: We define them using the suspend modifier. But, the suspend modifier by itself doesn’t do anything. It doesn’t make the function asynchronous. This should be called only from a coroutine or another suspend function
  • #47: They signify that that function will not block the caller thead.
  • #48: In order to enforce the convention, we have to use the withContext function. This function calls the specified suspending block with a given coroutine context, suspends until it completes, and returns the result. The withContext gets as a parameter a Dispatcher. The role of the dispatcher is to move the work to a different thread pool
  • #53: So in our login case, when we’re calling withContent(Dispatchers.IO), it means that we’re shifting the execution of the code block to a new thread.
  • #54: Suspension functions can only be called from other suspension functions or from coroutines. Coroutines allows us to write the code sequentially, without the need of callbacks.
  • #55: The code is now sequential.
  • #56: We can depend on data, for example here, we can depend on the auth token coming from authenticate and pass it to requestLogin
  • #57: Try and catch works as expected
  • #58: Let’s say that when the login button was pressed, we want to launch a coroutine to request the login, and then, once we got the response, we want to show the login status
  • #59: To launch a coroutine, we need to create a job and a coroutine scope, based on a dispatcher and the job.
  • #60: Then, based on the scope, we create a new coroutine by calling launch. Inside the coroutine block, we request the login The scope allows us to track all of the coroutines we’re creating
  • #61: Launch also allows us to set the dispatcher on which the coroutine is launched
  • #62: But, because we launched something, it also means we need to make sure we cancel the coroutines created at a certain point. For this we would use the cancel method from Job.
  • #63: What if the Activity gets destroyed before we got the response? We need to make sure that we’re cancelling the coroutine and not leaking any memory.
  • #64: So, this means that the lifecycle of a coroutine needs to be related to the lifecyle of another object - in Android the best place to launch coroutines is in VIewModels
  • #65: Then in onCleared we can cancel the job
  • #66: So, overall, this is how our viewmodel would look like. But, because this is a lot of boilerplate
  • #67: We have a new handy library: lifecycle-viewmodel-ktx
  • #68: The library adds a viewModelScope as an extension function of the ViewModel class. This scope is bound to Dispatchers.Main and will automatically be cancelled when the ViewModel is cleared. Instead of having to create a new scope in every ViewModel, you can just use viewModelScope and the library will take care of setting up and clearing the scope for you.
  • #69: Here’s what we’ve covered so far