안드로이드에서 코루틴은 어떻게 적용할 수 있을까?
: 코루틴 적용 및 ReactiveX(RxJava/RxKotlin)와 비교한다면?
권태환
요기요 / 안드로이드 개발
6년차 안드로이드 개발자 권태환입니다. 저는 꿈 많은 개발자가되자라는 블로그를 운영하고있고 GDG Seoul의 운영진을 하고 있습니다. 현재는 RGP Korea에서 요기요앱을 개발하고있으며, 안드로이드 개발 패턴과 코틀린에 흥미를 가지고 실무에도 적용하고 있습니다.
https://www.youtube.com/watch?v=QIRJKIDLZgU
Effective Java는 효율적이고 잘 설계된 Java 프로그램을 구현하기 위한 지침들을 소개하는 책입니다. Kotlin에서는 이 지침들이 잘 적용될 수 있는 설계를 갖추고 있는데요, Kotlin Reference 문서에서는 설명을 뒷받침하기 위해 이 책을 인용하기도 합니다. 세션에서는 "이펙티브 자바" 책의 규칙들을 짚어가면서, Kotlin에 어떻게 반영되었는지, 혹은 어떻게 적용될수 있는지에 대해 공유합니다.
Android is NOT just 'Java on Linux'.
Android uses Linux kernel. But only kernel. I show you how different Android is from normal Linux systems.
Visit this page.
http://kobablog.wordpress.com/2011/05/22/android-is-not-just-java-on-linux/
Get Your Node.js API Swaggering with OpenAPI SpecAdam Paxton
An overview of OpenAPI Spec, fka Swagger, as well as an example of how to use it when building a Node.js REST API.
Presented at Connect.tech Atlanta, September 21, 2017.
Google is adding Kotlin as an official programming language for Android development. Kotlin is a language that runs on the JVM and has full interoperability with Java. It costs nothing to adopt! I will show some cool features of Kotlin, how it makes developing with Android easy and finally we'll see what happens under the hood when we write in Kotlin.
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesLauren Yew
Kotlin Coroutines is a powerful threading library for Kotlin, released by JetBrains in 2018. At The New York Times, we recently migrated our core libraries and parts of our News app from RxJava to Kotlin Coroutines. In this talk we’ll share lessons learned and best practices to understand, migrate to, and use Kotlin Coroutines & Flows.
In this presentation, you will learn:
What Coroutines are and how they function
How to use Kotlin Coroutines & Flows (with real world examples and demos)
Where and why you should use Coroutines & Flows in your app
How to avoid the pitfalls of Coroutines
Kotlin Coroutines vs. RxJava
Lessons learned from migrating to Kotlin Coroutines from RxJava in large legacy projects & libraries
By the end of this talk, you will be able to apply Kotlin Coroutines to your own app, run the provided sample code yourself, and convince your team to give Kotlin Coroutines a try!
https://www.youtube.com/watch?v=QIRJKIDLZgU
Effective Java는 효율적이고 잘 설계된 Java 프로그램을 구현하기 위한 지침들을 소개하는 책입니다. Kotlin에서는 이 지침들이 잘 적용될 수 있는 설계를 갖추고 있는데요, Kotlin Reference 문서에서는 설명을 뒷받침하기 위해 이 책을 인용하기도 합니다. 세션에서는 "이펙티브 자바" 책의 규칙들을 짚어가면서, Kotlin에 어떻게 반영되었는지, 혹은 어떻게 적용될수 있는지에 대해 공유합니다.
Android is NOT just 'Java on Linux'.
Android uses Linux kernel. But only kernel. I show you how different Android is from normal Linux systems.
Visit this page.
http://kobablog.wordpress.com/2011/05/22/android-is-not-just-java-on-linux/
Get Your Node.js API Swaggering with OpenAPI SpecAdam Paxton
An overview of OpenAPI Spec, fka Swagger, as well as an example of how to use it when building a Node.js REST API.
Presented at Connect.tech Atlanta, September 21, 2017.
Google is adding Kotlin as an official programming language for Android development. Kotlin is a language that runs on the JVM and has full interoperability with Java. It costs nothing to adopt! I will show some cool features of Kotlin, how it makes developing with Android easy and finally we'll see what happens under the hood when we write in Kotlin.
Threading Made Easy! A Busy Developer’s Guide to Kotlin CoroutinesLauren Yew
Kotlin Coroutines is a powerful threading library for Kotlin, released by JetBrains in 2018. At The New York Times, we recently migrated our core libraries and parts of our News app from RxJava to Kotlin Coroutines. In this talk we’ll share lessons learned and best practices to understand, migrate to, and use Kotlin Coroutines & Flows.
In this presentation, you will learn:
What Coroutines are and how they function
How to use Kotlin Coroutines & Flows (with real world examples and demos)
Where and why you should use Coroutines & Flows in your app
How to avoid the pitfalls of Coroutines
Kotlin Coroutines vs. RxJava
Lessons learned from migrating to Kotlin Coroutines from RxJava in large legacy projects & libraries
By the end of this talk, you will be able to apply Kotlin Coroutines to your own app, run the provided sample code yourself, and convince your team to give Kotlin Coroutines a try!
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
Author: Oleg Godovykh, eastbanctech.com
Kotlin is a new programming language built by Jetbrains and is a new member of JVM family. As opposed to typical reason to introduce some new language, Kotlin main goal isn't to create new paradigm or fill a new niche, but to make routine tasks much easier and safer. Kotlin gains popularity across Android developer community, and in this presentation it is shown how Kotlin usage can dramatically simplify typical mobile app development.
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaJAX London
2011-11-02 | 03:45 PM - 04:35 PM |
Android Activities can possess one of four launch modes and one of many activity tasks. We will explore how your choices of launch modes and tasks affect your Applications back stack history and what will happen behind the scenes. After this talk you will confidently be able to wield the best launch modes for your apps activities in every situation!
A step towards the way you write the code in React application.In this presentation, I have given introduction about React hooks. Why we need it in our react applications and describe about the two most commonly used React Hooks API useState and useEffect. I also given the links of code snippets I added in these slides
With the announcement on officially supporting Kotlin for Android, this presentation tries to compare Java and Kotlin to encourage people to switch to Kotlin
If you still haven't heard of it, there is a new star in JVM sky - Kotlin. This short presentation will serve as intro for those who wan't to hear what's all the fuss about and dive deeper into this new alternative to Java
Slides accompanying a presentation on Dropwizard I gave at the DevIgnition conference ( www.devignition.com ) on April 29, 2016. The sample code is on GitHub at https://github.com/sleberknight/dropwizard-devignition-2016
Jetpack Compose is a Declarative UI toolkit written in 100% Kotlin. What is Declarative UI? Why should we use it? We will talk about data flow and the benefits of Declarative UI. Then we’ll show the way to setup Jetpack Compose, write some basic samples and let it works with the MVVM architecture.
Kotlin Basics & Introduction to Jetpack Compose.pptxtakshilkunadia
In our fast and ever-changing world of tech, creating a great UI is not just indispensable but also an obligation as a developer. A great UI makes the whole experience of accessing the products/services an absolute pleasure.
Hour 1: Basics of Kotlin
Hour 2: Introduction to Jetpack Compose Development Kit
Introduction to Koltin for Android Part I Atif AbbAsi
Welcome to Android Basics in Kotlin! In this course, you'll learn the basics of building Android apps with the Kotlin programming language. Along the way, you'll develop a collection of apps to start your journey as an Android developer.
Introduction to Kotlin Language and its application to Android platformEastBanc Tachnologies
Author: Oleg Godovykh, eastbanctech.com
Kotlin is a new programming language built by Jetbrains and is a new member of JVM family. As opposed to typical reason to introduce some new language, Kotlin main goal isn't to create new paradigm or fill a new niche, but to make routine tasks much easier and safer. Kotlin gains popularity across Android developer community, and in this presentation it is shown how Kotlin usage can dramatically simplify typical mobile app development.
Android | Android Activity Launch Modes and Tasks | Gonçalo SilvaJAX London
2011-11-02 | 03:45 PM - 04:35 PM |
Android Activities can possess one of four launch modes and one of many activity tasks. We will explore how your choices of launch modes and tasks affect your Applications back stack history and what will happen behind the scenes. After this talk you will confidently be able to wield the best launch modes for your apps activities in every situation!
A step towards the way you write the code in React application.In this presentation, I have given introduction about React hooks. Why we need it in our react applications and describe about the two most commonly used React Hooks API useState and useEffect. I also given the links of code snippets I added in these slides
With the announcement on officially supporting Kotlin for Android, this presentation tries to compare Java and Kotlin to encourage people to switch to Kotlin
If you still haven't heard of it, there is a new star in JVM sky - Kotlin. This short presentation will serve as intro for those who wan't to hear what's all the fuss about and dive deeper into this new alternative to Java
Slides accompanying a presentation on Dropwizard I gave at the DevIgnition conference ( www.devignition.com ) on April 29, 2016. The sample code is on GitHub at https://github.com/sleberknight/dropwizard-devignition-2016
Jetpack Compose is a Declarative UI toolkit written in 100% Kotlin. What is Declarative UI? Why should we use it? We will talk about data flow and the benefits of Declarative UI. Then we’ll show the way to setup Jetpack Compose, write some basic samples and let it works with the MVVM architecture.
Kotlin Basics & Introduction to Jetpack Compose.pptxtakshilkunadia
In our fast and ever-changing world of tech, creating a great UI is not just indispensable but also an obligation as a developer. A great UI makes the whole experience of accessing the products/services an absolute pleasure.
Hour 1: Basics of Kotlin
Hour 2: Introduction to Jetpack Compose Development Kit
Introduction to Koltin for Android Part I Atif AbbAsi
Welcome to Android Basics in Kotlin! In this course, you'll learn the basics of building Android apps with the Kotlin programming language. Along the way, you'll develop a collection of apps to start your journey as an Android developer.
본 장표는 인프콘 2022 / 코틀린 멀티플랫폼, 미지와의 조우 세션에 대한 강연 자료입니다.
코틀린은 멀티플랫폼을 지원하는 언어로 Server-side와 Android뿐만이 아니라 JavaScript 엔진이 있는 브라우저나 Node.js도 지원하며, Native 등 다양한 플랫폼에서 쓸 수 있습니다. 이를 이용해 코틀린 코드를 공유하는 단일 코드베이스로 모바일부터 웹과 데스크톱, 서버에 이르기까지 다중 플랫폼 애플리케이션을 작성할 수 있습니다.
본 핸즈온 세션을 통해 코틀린 멀티플랫폼과 함께 리액트, 스프링부트로 웹 애플리케이션의 프론트엔드부터 백엔드까지 직접 개발하며 친해져 보는 시간을 가져보세요. 참가자는 코틀린 멀티플랫폼 프로젝트를 이해하고, 더 나아가 프론트엔드와 백엔드 간의 공유 로직 작성, Kotlin/JS 기반 리액트 및 스프링 웹 프로그래밍을 경험할 수 있습니다.
https://github.com/arawn/building-fullstack-webapp-with-kotlin-multiplatform
https://infcon.day/speaker/박용권-김지헌-코틀린-멀티플랫폼/
GDB와 strace로 Hang 걸린 Python Process 원격 디버깅Youngmin Koo
Python 프로그램을 디버깅하실 때 어떤 툴을 사용하시나요? 아무래도 가장 많이 사용하고 계신 툴은 PyCharm이 아닐까 싶습니다. PyCharm은 JetBrains에서 만든 GUI 환경에서 사용할 수 있는 Python IDE입니다.
PyCharm은:
로컬 컴퓨터에서 디버깅 모드로 (PyDev로) Python 프로세스를 실행할 수 있습니다.
로컬 컴퓨터에서 실행 중인 Python 프로세스에 Attach해 디버깅할 수 있습니다.
원격 서버에서 디버깅 모드로 (PyDev로) Python 프로세스를 실행할 수 있습니다.
하지만 원격에서 동작하고 있는 프로세스에 디버거를 Attach하는 기능은 제공하지 않고 있습니다. 또한 Python 디버깅 모듈인 pdb를 사용하여도 동작하고 있는 프로세스에 Attach하는 것은 지원하고 있지 않습니다.
로컬 환경에서는 문제 없이 돌아갔던 Python 프로그램이 원격 서버에서는 아무런 로그 없이 멈춰 버리는 경우 어디서부터 손을 대야 할지 정말 막막합니다. 이 때 GDB와 strace를 이용하면 어디에서 문제가 발생했는지 진단할 수 있습니다. 이 세션에서는 GDB와 strace를 이용해 디버깅하여 원격 리눅스 서버에서 Python Process가 Hang 되어 버리는 문제를 진단하고 해결했던 경험을 공유하려고 합니다.
[C++ Korea 3rd Seminar] 새 C++은 새 Visual Studio에, 좌충우돌 마이그레이션 이야기Chris Ohk
C++11을 시작으로 모던 C++이 도입된 지도 어느새 6년이라는 시간이 흘렀습니다. 올해는 C++17 표준이 도입될 예정입니다. 그만큼 많이 개선되고 새로운 기능들이 많이 도입되었기에 실무에서 사용해보고 싶은 경우도 많습니다. 하지만 이미 서비스 중이라 기존 프로젝트를 새 버전의 VS로 마이그레이션하기 어려운 프로젝트가 많습니다. 그렇다고 아예 불가능한 일도 아닙니다. 이번 세미나에서는 기존 프로젝트를 새 버전의 VS로 마이그레이션하면서 발생했던 문제와 마이그레이션 이후 모던 C++을 사용하면서 발생했던 문제, 그리고 해결법을 설명하고자 합니다. 또한 새 버전의 VS에 생긴 유용한 기능들도 함께 알려드립니다.
비행기 설계를 왜 통일 해야 할까?
디자인 시스템을 하는 이유
비행기들이 다 용도가 다르다...어떻게 설계하지?
맥락이 다른 페이지와 패턴
경유지까지 아직 멀었다... 언제 수리하지?
디자인 시스템을 적용하는 시점
엔지니어랑 얘기해서 정비해야하는데...어떻게 수리하지?
디자인 시스템을 적용하는 프로세스
비행기 설계가 바뀐걸 어떻게 알리지?
디자인 시스템의 전파
8. 저희는
Kotlin extensions + Higher-Order function
Coroutines 적용
버튼 클릭 처리
요기요 Java : 59.9% / Kotlin : 39.9%
9. Google 발표 자료
In fact, 27% of the top 1,000 Android apps on Google Play already use
Kotlin.
More importantly, Android developers are loving the language with over
97% satisfaction in our most recent survey. It's no surprise that Kotlin
was voted as the #2 most-loved language in the 2018 StackOverflow
survey.
출처 : https://android-developers.googleblog.com/2018/10/kotlin-momentum-for-android-and-beyond.html
12. Subroutine
In computer programming, a subroutine is a sequence of program
instructions that performs a specific task, packaged as a unit
In different programming languages, a subroutine may be called a
procedure, a function, a routine, a method, or a subprogram. The generic
term callable unit is sometimes used.
출처 : https://en.wikipedia.org/wiki/Subroutine
13. Subroutine
fun test() fun MutableList<Int>.sum()
mutableList().sum()
return sum()
subroutine의 return이 불러지기 전까진
test()의 다음 라인을 실행하지 않는다.
14. Subroutine example
private fun MutableList<Int>.sum(): Int =
this.sumBy { it }
@Test
fun test() {
val sum = (0..10).toMutableList().sum()
println(sum)
}
sum이 끝나야 return
sum이 끝나야 println
15. Coroutines
According to Donald Knuth, Melvin Conway coined the term coroutine in
1958 when he applied it to construction of an assembly program.
The first published explanation of the coroutine appeared later, in 1963
출처 : https://en.wikipedia.org/wiki/Coroutine
16. Coroutines
Coroutines are computer-program components that
generalize subroutines for non-preemptive multitasking, by allowing
multiple entry points for suspending and resuming execution at certain
locations. Coroutines are well-suited for implementing familiar program
components such as cooperative tasks, exceptions, event
loops, iterators, infinite lists and pipes.
출처 : https://en.wikipedia.org/wiki/Coroutine
20. Coroutines
Entry point 여러 개 허용하는 subroutine
no. 1 Out 0 .. no. 2 Out 0 .. no. 4 Out 5 .. no. 5 Out 5
End no. 1 Done! .. no. 9 Out 4 .. End no. 2 Done! .. no. 6 Out 5
End no. 3 Done! .. End no. 4 Done! .. no. 8 Out 5 .. End no. 5 Done!
no. 9 Out 5 .. End no. 6 Done! .. no. 10 Out 5 .. End no. 7 Done!
no. 11 Out 5 .. End no. 8 Done! .. no. 12 Out 5 .. End no. 9 Done!
21. Coroutines
Start routine fun Int.countDown()
Loop
fun Int.countDown()
Loop
fun Int.countDown()
Loop
fun Int.countDown()
Loop
10.countDown()
.
.
.
Entry point 여러 개 허용하는 subroutine
22. Coroutines example
private suspend fun Int.countDown(currentIndex: Int) {
for (index in this downTo 1) { // countdown from 10 to 1
tv_message.text = "Now index $currentIndex Countdown $index" // update text
delay(200)
}
Log.i("TEMP", "Now index $currentIndex Done!")
}
Thread[main,5,main]
Android UI
Entry point 여러 개 허용하는 subroutine
var currentIndex = 0
fab.onClick {
CoroutineScope(Dispatchers.Main).launch {
10.countDown(++currentIndex)
}
}
25. Kotlin coroutines
Kotlin 다양한 platform 제공
Server-side
Desktop
Mobile Application
다양한 언어에서 제공하던 주요 라이브러리 제공
C#, ECMAScript : async/await
Go : channels, select
C#, Python : generators/yield
더 자세한 내용은 https://kotlinlang.org/docs/reference/coroutines-overview.html
Coroutine
light-weight threads
29. Kotlin coroutines
@Test
fun test() {
GlobalScope.launch { // launch new coroutine in background and continue
delay(300L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(500L) // block main thread for 2 seconds to keep JVM alive
}
blocking과 non-blocking
Main Thread에서 Thread.sleep(500L)을 부르면
0.5초동안 앱이 멈추는 현상 발생 후 넘어간다.
32. Kotlin coroutines
runBlocking은 함수의 처리가 끝날때까지 대기
delay()를 걸어두면 delay 시간만큼 대기하고 return
Android에서 runBlocking을 UI에서 잘못 사용하면 멈추는 현상 발생
runBlocking
delay를 이용해 non-blocking을 할 수 있음
runBlocking, CoroutineScope, GlobalScope 안에서 동작해야 함
delay
35. Kotlin coroutines
가장 기본적인 Scope
Thread 형태를 지정(Main, Default, IO 등을 지정)
CoroutineScope(Main, Default, IO …).
launch, async 등을 통해 scope을 실행
CoroutineScope
36. Kotlin coroutines
Activity/Fragment Lifecycle에 따라야 한다
onDestroy() : cancel 하도록 코드 추가
CoroutineScope(/* thread type */).launch {}로 실행
launch {}의 return job의 동작을 지정 가능
join() : scope 동작이 끝날때까지 대기하며, suspend에서 호출 가능
cancel() : 동작을 종료하도록 호출
start() : scope이 아직 시작하지 않을 경우 start, scope의 상태를 확인
CoroutineScope 중요한 점
37. Kotlin coroutines
@Suppress("FunctionName")
public fun CoroutineScope(context: CoroutineContext): CoroutineScope =
ContextScope(if (context[Job] != null) context else context + Job())
CoroutineScope의 interface 정의
public interface CoroutineScope {
@Deprecated(level = DeprecationLevel.HIDDEN, message = "Deprecated in favor of
top-level extension property")
public val isActive: Boolean
get() = coroutineContext[Job]?.isActive ?: true
/**
* Context of this scope. */
public val coroutineContext: CoroutineContext
}
38. Kotlin coroutines
@Test
fun test() = runBlocking {
CoroutineScope(Dispatchers.Unconfined).launch {
delay(300L)
println("World!")
}
println("Hello,")
delay(500L)
}
CoroutineScope 활용
Delay 대신 coroutine의 return인 job.join()을 사용
39. Kotlin coroutines
@Test
fun test() = runBlocking {
delay(300L)
println("World!")
}
println("Hello,")
}
CoroutineScope 활용 - Delay 대신 job.join()
delay(500L)
CoroutineScope(Dispatchers.Unconfined).launch {
job.join()
val job =
40. Kotlin coroutines
@Test
fun test() = runBlocking {
val job = CoroutineScope(Dispatchers.Unconfined).launch {
delay(300L)
println("World!")
}
println("Hello,")
job.join()
}
CoroutineScope 활용
새로운 scope을 생성하고
default로 launch
launch에서 CoroutineScope에서
지정한 default Thread로 사용
join()으로 default thread 종료하기 전까지 대기
42. Kotlin coroutines
CoroutineScope 상속 받아 구현
Demon, Application 등에서 사용
Application의 lifetime에 따라 동작하는 scope에서 사용 추천
GlobalScope는 Dispatchers.Unconfined(worker thread)에서 동작
GlobalScope.launch(/* thread type */) {}로 실행
GlobalScope
43. Kotlin coroutines
object GlobalScope : CoroutineScope {
/**
* @suppress **Deprecated**: Deprecated in favor of top-level extension property
*/
@Deprecated(level = DeprecationLevel.HIDDEN,
message = "Deprecated in favor of top-level extension property")
override val isActive: Boolean
get() = true
/**
* Returns [EmptyCoroutineContext].
*/
override val coroutineContext: CoroutineContext
get() = EmptyCoroutineContext
}
GlobalScope API 코드
44. Kotlin coroutines
fun ReceiveChannel<Int>.sqrt(): ReceiveChannel<Double> =
for (number in this@sqrt) {
send(Math.sqrt(number.toDouble()))
}
GlobalScope 사용 예
GlobalScope.produce(Dispatchers.Unconfined) {
}
49. Kotlin coroutines
CoroutineScope의 return에는 job 객체를 넘겨준다.
이 job을 통해 routine의 취소, 실행, 종료를 대기할 수 있다
job.cancel() : 종료하도록 유도한다
job.join() : 종료를 대기하며 호출은 suspend에서 가능하다
job.start() : coroutine의 시작을 확인할 수 있으며, 시작 상태라면 true
Job
51. Kotlin coroutines
var currentIndex = 0
fab.onClick {
CoroutineScope(Dispatchers.Default).launch {
val job = launch(Dispatchers.Main) {
10.countDown(++currentIndex)
}
job.join()
}
}
private suspend fun Int.countDown(currentIndex: Int) {
for (index in this downTo 1) { // countdown from 10 to 1
tv_message.text = "Now index $currentIndex Countdown $index" // update text
delay(200)
}
Log.i("TEMP", "Now index $currentIndex Done!")
}
Count down
새로운 scope을 생성하고
default로 launch
launch를 Main Thread로 변경
join()으로 UI thread 종료하기 전까지 대기
상위 scope thread에 따름
여기서는 UI
55. Android onClick - RxJava vs coroutines
Observable과 Streams
기존 Thread 보다 간단한 코드로 처리
stream을 통해 데이터 처리 용이
Thread간 교체가 간단
RxJava를 활용한 수 많은 라이브러리 활용
가능
러닝커브가 높음
용어를 모르면 코드 활용 이유를 알 수 없음
RxJava Kotlin coroutines
함수 형태라 읽기 쉽다
light-weight threads
모든 routine 동작을 개발자가 처리 가능
아직은 필요한 라이브러리를 구현해서 사용
해야 함
RxView와 같은 라이브러리 개발 필요
56. Android onClick - RxJava vs coroutines
private val clickEventSubject =
PublishSubject.create<View>()
private var currentIndex = 0
fab.setOnClickListener {
clickEventSubject.onNext(it)
}
clickEventSubject
.throttleFirst(500, TimeUnit.MICROSECONDS)
.observeOn(Schedulers.io())
.map {
currentIndex++
}
.switchMap {
Observable.zip(Observable.range(0, 10),
Observable.interval(200, TimeUnit.MILLISECONDS),
BiFunction<Int, Long, Int> { range, _ ->
10 - range
})
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ index ->
tv_message.text = "Now index $currentIndex Countdown
$index"
}, {})
RxJava Countdown 구현
var currentIndex = 0
fab.onClick {
}
private suspend fun Int.countDown(currentIndex: Int) {
Log.i("TEMP", "Now index $currentIndex Done!")
}
CoroutineScope(Dispatchers.Default).launch {
val job = launch(Dispatchers.Main) {
10.countDown(++currentIndex)
}
job.join()
}
for (index in this downTo 1) {
}
tv_message.text = "Now index $currentIndex
Countdown $index"
delay(200)
Coroutines Countdown 구현
어느게 읽기(이해하기) 더 쉽나요?
한번 읽어보죠
57. Android onClick - RxJava vs coroutines
private val clickEventSubject =
PublishSubject.create<View>()
private var currentIndex = 0
fab.setOnClickListener {
clickEventSubject.onNext(it)
}
clickEventSubject
.throttleFirst(500, TimeUnit.MICROSECONDS)
.observeOn(Schedulers.io())
.map {
currentIndex++
}
.switchMap {
Observable.zip(Observable.range(0, 10),
Observable.interval(200, TimeUnit.MILLISECONDS),
BiFunction<Int, Long, Int> { range, _ ->
10 - range
})
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ index ->
tv_message.text = "Now index $currentIndex Countdown
$index"
}, {})
RxJava Countdown 구현
var currentIndex = 0
fab.onClick {
}
private suspend fun Int.countDown(currentIndex: Int) {
Log.i("TEMP", "Now index $currentIndex Done!")
}
CoroutineScope(Dispatchers.Default).launch {
val job = launch(Dispatchers.Main) {
10.countDown(++currentIndex)
}
job.join()
}
for (index in this downTo 1) {
}
tv_message.text = "Now index $currentIndex
Countdown $index"
delay(200)
Coroutines Countdown 구현
58. Android onClick - RxJava vs coroutines
처음 학습 비용이 높다
수 많은 라이브러리 활용 가능
예제도 많고, 문서도 잘 되어있다.
RxJava Kotlin coroutines
처음 학습 비용이 낮다
아직은 부족한 라이브러리
직접 만들 수 있고, 문서도 잘 되어있다
60. Android onClick 잘 활용하기
첫 번째 이벤트 만 허용하기 위해서
throttleFirst 활용
시간으로 first의 시간을 지정하여 아래와 같은 문제 발생
해결 : 데이터 처리가 끝나면 버튼의 상태를 변경
중간에 오류날 가능성을 대비한 예외처리 필요
RxJava 버튼 처리
61. Android onClick 잘 활용하기
첫 번째 이벤트 만 허용하기 위해서
버튼의 상태를 변경해서 처리한다?
다행히도 coroutine에서는 그럴 필요 없다.
Coroutine으로 처리
63. Android onClick 잘 활용하기
private fun View.onClick(action: suspend (View) -> Unit) {
val event = GlobalScope.actor<View>(Dispatchers.Main) {
for (event in channel) action(event)
}
setOnClickListener {
event.offer(it)
}
}
var currentIndex = 0
fab.onClick {
10.countDown(currentIndex++)
}
Coroutine GlobalScope.actor<T> 활용하기
1. Singletone의 GlobalScope 활용
2. actor 이용 event 받기
3. actor에 offer로 event 보내기
4. 받은 event를 Higher-Order function으로 넘겨서 정의하도록 한다.
6. 람다 표현으로 countDown 구현
5. 이때 Higher-Order function 정의는 suspend가 포함되어야 한다
66. UnitTest/Main Thread에서 활용하기 쉽게 Dispatchers 하나로 활용
UnitTest에서 Main thread를 활용할 수 없기에 기본으로 처리 할 수 있도록 작성
CoroutineScope을 Base에 작성하여 release를 쉽게 하도록 처리
onClick에 coroutine 활용을 위한 GlobalScope 적용
안드로이드에서 코루틴 활용
Android Coroutines
67. Android Coroutines
sealed class DispatchersProviderSealed {
open val main: CoroutineContext by lazy { Dispatchers.Main }
open val default: CoroutineContext by lazy { Dispatchers.Default }
}
/**
* 기타 Thread를 위한 Dispatchers 정의
*/
object DispatchersProvider : DispatchersProviderSealed()
/**
* Unit Test를 위한 Dispatchers 정의
*/
object TestDispatchersProvider : DispatchersProviderSealed() {
override val main: CoroutineContext = Dispatchers.Unconfined
override val default: CoroutineContext = Dispatchers.Unconfined
}
Dispatchers 정의(UnitTest/Default Thread)
68. Android Coroutines
abstract class CoroutineScopeActivity : AppCompatActivity(), CoroutineScope {
private val job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}
CoroutineScope을 상속받아 구현
onDestroy()에서 job을 종료하도록 한다.
Job을 미리 생성하여
CoroutineContext에 미리 지정 할 수 있다.
Activity에서 사용할 기본 Context를 정의한다.
69. CoroutineScope을 상속받아 구현하면 기본 CoroutineScope으로 정의되어있다
launch, actor<E>을 사용하면 코드 간결 및 자동으로 종료 처리 해준다.
Default 상위 Activity에서 정의한 CoroutineScope의 Thread를 활용한다
필요시 launch, actor에서 Thread를 언제든 변경 가능하다
다양한 CoroutineScope 구현
ViewModel
LifecycleObservable
Fragment
CoroutineScope을 상속받아 구현
Android Coroutines
70. Android Coroutines
abstract class CoroutineScopeActivity : CoroutineScopeActivity() {
launch {
// UI Thread에서 처리
}
launch(Dispatchers.Default) {
// Default Thread에서 처리
}
actor<Generic Type> {
// UI Thread에서 event 처리
for (event in channel) action(event)
}
actor<Generic Type>(Dispatchers.Default) {
// Default Thead에서 처리
for (event in channel) action(event)
}
}
CoroutineScope 상속 받은 Activity에서 routine 사용하기
launch, actor에서는 언제든지
Thread type을 변경할 수 있다.
71. Higher-Order function + kotlin Extensions을 활용
GlobalScope을 활용하거나, CoroutineScope을 활용 할 수 있다
동작 범위에 따라서 GlobalScope, CoroutineScope을 선택함이 좋다
onClick 처리
Android Coroutines
72. Android Coroutines
class CoroutinesSendChannelOnClickEvent<E>(
private val view: View,
private val bgBody: suspend (item: View) -> E,
private val dispatcherProvider: DispatchersProviderSealed = DispatchersProvider,
private val job: Job? = null) {
fun consumeEach(uiBody: (item: E) -> Unit): CoroutinesSendChannelOnClickEvent<E> {
val clickActor = CoroutineScope(dispatcherProvider.main + (job
?: EmptyCoroutineContext)).actor<View> {
this.channel.map(context = dispatcherProvider.default, transform = bgBody).consumeEach(uiBody)
}
view.setOnClickListener { clickActor.offer(it) }
return this
}
}
fun <E> View.onClick(dispatcherProvider: DispatchersProviderSealed = DispatchersProvider,
job: Job? = null, bgBody: suspend (item: View) -> E): CoroutinesSendChannelOnClickEvent<E> =
CoroutinesSendChannelOnClickEvent(this, bgBody, dispatcherProvider, job)
infix fun <E> CoroutinesSendChannelOnClickEvent<E>.consume(uiBody: (item: E) -> Unit) {
this.consumeEach(uiBody)
}
onClick 만들기, background에서 처리하고, UI에 던져주기
View : click을 위한 View
background : Higher-Order Function
Provider : 지정
Job : 종료 처리를 위한 job 추가
Offer 처리를 위한 CoroutineScope 생성
생성을 간단하게 하기 위한 function 2개
74. 이미 JakeWharton 배포.
Dependency 추가
implementation ‘com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
Deferred<E>를 활용하여 return을 처리할 수 있다.
Retrofit2 kotlin coroutines adapter
Android Coroutines
interface RetrofitService {
@GET("/posts")
fun getPosts(): Deferred<Response<List<Post>>>
}
76. Android Coroutines
launch {
val request = service.getPosts()
val response = request.await()
if (response.isSuccessful) {
// Pass in the response.body() to your adapter
} else {
toast("Error ${response.code()}")
}
}
Retrofit2 kotlin coroutines adapter