깨알 개념/Kotlin 25

[Kotlin] Coroutines Flow - StateFlow

#1 개요 StateFlowA SharedFlow that represents a read-only state with a single updatable data value that emits updates to the value to its collectors. A state flow is a hot flow because its active instance exists independently of the presence of collectors. Its current valukotlinlang.orgSharedFlow의 일종인 StateFlow에 대해 살펴본다. #2 SharedFlow와의 비교이름에서 알 수 있듯, StateFlow는 기존 SharedFlow에 State의 특성을 결합한 Flow다..

[Kotlin] Coroutines Flow - Intermediate operator

#1 개요#1-1 중간 연산자 (Intermediate operator) Asynchronous Flow | Kotlin kotlinlang.org중간 연산자에 대해 살펴본다. #1-2 중간 연산자의 구조중간 연산자는 이름 그대로의 역할을 수행한다. 이름에 있는 '중간'은, emit과 collect 사이 '중간'을 의미한다. 시작점이 emit이고 도착점이 collect인 배수관 속 물의 흐름을 intermediate operator가 하이재킹하는 느낌이라고 보면 된다. 여기서 중요한 점은, 앞으로(=미래에) emit될 데이터를 변형하는 연산자는 결코 아니라는 것이다. 이미(=과거에) emit된 데이터에 특정 연산을 가하여, collect에 전달하는 연산자다. 중간 연산자이니 말이다. #2 Flow에 가용..

[Kotlin] Coroutines Flow - Back pressure와 그 처리

#1 개요Coroutines Flow를 사용할 때 생길 수 있는 현상인 백 프레셔(Back pressure)에 대해 살펴본다. 또, 백 프레셔를 처리하는 방법도 살펴본다. 이 때, 백 프레셔는 에러가 아닌 자연스러운 현상일 뿐이다. 따라서, 백 프레셔를 해결한다는 표현은 정확하지 않다. 백 프레셔에 대처한다는 표현이 옳다. #2 백 프레셔#2-1 백 프레셔가 없는 코드import kotlinx.coroutines.*import kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.flow// 1초마다 1씩 증가하는 countfun startCountUp(count: Mu..

[Kotlin] Coroutines Flow - 기초

#1 Coroutines Flow#1-1 개요 FlowFlow An asynchronous data stream that sequentially emits values and completes normally or with an exception. Intermediate operators on the flow such as map, filter, take, zip, etc are functions that are applied to the upstream flow or flows and return a dokotlinlang.orgFlow는 내부적으로 Coroutine을 사용해 비동기적으로 데이터 스트림을 처리하는 API다. 이를 반응형 프로그래밍이라고도 한다. 반응형 프로그래밍을 한 마디로 정의하면, ..

[Kotlin] Coroutines - 한 Scope 내에서의 계층 관계

#1 이전 글 [Kotlin] Coroutines - Coroutine builder#1 Coroutine builder kotlinx-coroutines-coreCore primitives to work with coroutines. Coroutine builder functions: Coroutine dispatchers implementing CoroutineDispatcher: More context elements: Synchronization primitives for coroutines: Top-level suspendinkenel.tistory.com위 게시글의 CoroutineScope의 생략에 대해 다룬 #6-4에서 이어지는 글이다. 이전 글에선 CoroutineScope을 생략하는 게..

[Kotlin] 위임 프로퍼티 (Delegated properties)

#1 Delegated properties#1-1 개요 Delegated properties | Kotlin kotlinlang.org위임 프로퍼티는, getter와 setter 로직을 다른 클래스에 위임(delegate)하는 코틀린 프로퍼티를 의미한다. 본 게시글에서는 위임 프로퍼티의 기제에 대해 탐구하고 또 위임 프로퍼티를 간단히 구현해본다. #1-2 위임(delegate)의 의미 [Kotlin] 프로퍼티(Property)#1 필드와 프로퍼티 #1-1 프로퍼티의 개념 // Java String name = "steve"; // Field System.out.println("my name is" + name); name = "kevin"; --- // Kotlin var name : String = "..

[Kotlin] Coroutines - ViewModelScope

본 게시글의 Coroutine 개념은 Android 내에서 사용되는 것을 전제로 작성되었다. #1 ViewModel 속 전통적인 방식의 Coroutinesimport androidx.lifecycle.ViewModelimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.launchclass SampleViewModel : ViewModel() {    private val myJob = Job()    private val myScope = CoroutineScope(Dispatchers.IO + myJob)    fun s..

[Kotlin] Coroutines - 스레드 전환

본 게시글의 Coroutine 개념은 Android 내에서 사용되는 것을 전제로 작성되었다. #1 Background Thread의 한계 - UI 조작 불가능...class MainActivity : AppCompatActivity() {    ...    override fun onCreate(savedInstanceState: Bundle?) {        ...        btnDwCoroutine.setOnClickListener {            CoroutineScope(Dispatchers.IO).launch {                downloadData()            }        }    }    private fun downloadData() {        ..

[Kotlin] Coroutines - Parallel Decomposition

#1 작업의 처리 방식#1-1 가정위와 같은 총 7개의 작업이 있다고 가정한다. 각 작업이 소요 시간은 5, 10, 15, 10, 20, 25, 5다. #1-2 전통적인 방법전통적인 방법은 선형적(Serial)으로 작업을 수행한다. #1-3 전통적인 방법의 구현import kotlinx.coroutines.*data class Food(val name: String, val cookingTimeInSeconds: Long)suspend fun cook(food: Food) { delay(1000 * food.cookingTimeInSeconds) println("${food.name} 완료")}fun main() { val foods = arrayOf( Food("국밥", 5..