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

Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMashleypuls
 
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
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code ExamplesNaresh Chintalcheru
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016Frank Lyaruu
 
Java7 - Top 10 Features
Java7 - Top 10 FeaturesJava7 - Top 10 Features
Java7 - Top 10 FeaturesAndreas Enbohm
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsNeo4j
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesHaim Yadid
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.JustSystems Corporation
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developersJohn Stevenson
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 

What's hot (20)

Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASM
 
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
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
JDK1.6
JDK1.6JDK1.6
JDK1.6
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
 
Java7 - Top 10 Features
Java7 - Top 10 FeaturesJava7 - Top 10 Features
Java7 - Top 10 Features
 
Scala
ScalaScala
Scala
 
Utilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and OperationsUtilizing Powerful Extensions for Analytics and Operations
Utilizing Powerful Extensions for Analytics and Operations
 
Hybrid Applications
Hybrid ApplicationsHybrid Applications
Hybrid Applications
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 

Similar to Exploring Kotlin

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android DevelopmentSpeck&Tech
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationAjax Experience 2009
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applicationsrohitnayak
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaDILo Surabaya
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomyDongmin Yu
 
XML-Free Programming
XML-Free ProgrammingXML-Free Programming
XML-Free ProgrammingStephen Chin
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio
 
Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorTrayan Iliev
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
Groovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsGroovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsIndicThreads
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 

Similar to Exploring Kotlin (20)

Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
Laurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus PresentationLaurens Van Den Oever Xopus Presentation
Laurens Van Den Oever Xopus Presentation
 
Groovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web ApplicationsGroovy & Grails: Scripting for Modern Web Applications
Groovy & Grails: Scripting for Modern Web Applications
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Presto anatomy
Presto anatomyPresto anatomy
Presto anatomy
 
XML-Free Programming
XML-Free ProgrammingXML-Free Programming
XML-Free Programming
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Kotlin Coroutines and Rx
Kotlin Coroutines and RxKotlin Coroutines and Rx
Kotlin Coroutines and Rx
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and Ktor
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
Groovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applicationsGroovy - Grails as a modern scripting language for Web applications
Groovy - Grails as a modern scripting language for Web applications
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 

Recently uploaded

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 

Recently uploaded (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 

Exploring Kotlin

Editor's Notes

  1. 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.
  2. 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.
  3. The project started at 2010. In 2017 it was acknowledged by Google as a first-class citizen on Android.
  4. Kotlin usage and Kotlin community is growing very fast.
  5. One can compile Kotlin code for different platforms, including JVM, Android, JavaScript and Native.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. You can share the code written for different platforms by using Kotlin Multiplatform.
  11. Now we will talk about some of Kotlin’s coolest features, I have tried to keep them beginner friendly.
  12. 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.
  13. Collection types, such as Iterable, Collection, List, Set, Map
  14. This is lambda expression that is saved in the argument
  15. Stld contains tons of such funtions
  16. 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.
  17. 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
  18. 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
  19. 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.
  20. 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
  21. When working with callbacks it’s easy to get in a callback hell, decreasing the readability of the code.
  22. And, guess what, that show needs to be on the UI so we need to get a reference to the main looper
  23. If we’re not creating a new thread for our login request, the code looks something like this:
  24. But if we’re running this on the UI thread but We’re blocking the thread
  25. Only after the login is returned, we can unblock our thread and draw the UI again
  26. 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.
  27. That’s what a coroutine is - an instance of a suspendable computation.
  28. Function A has to be completed before Function B continue. The thread is locked for Function A to complete it’s execution.
  29. 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.
  30. Coroutines allow us to write async code sequentially
  31. 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.
  32. 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
  33. The points in the code where we want to suspend the execution, are called suspension points
  34. 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
  35. They signify that that function will not block the caller thead.
  36. 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
  37. 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.
  38. 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.
  39. The code is now sequential.
  40. We can depend on data, for example here, we can depend on the auth token coming from authenticate and pass it to requestLogin
  41. Try and catch works as expected
  42. 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
  43. To launch a coroutine, we need to create a job and a coroutine scope, based on a dispatcher and the job.
  44. 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
  45. Launch also allows us to set the dispatcher on which the coroutine is launched
  46. 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.
  47. 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.
  48. 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
  49. Then in onCleared we can cancel the job
  50. So, overall, this is how our viewmodel would look like. But, because this is a lot of boilerplate
  51. We have a new handy library: lifecycle-viewmodel-ktx
  52. 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.
  53. Here’s what we’ve covered so far