In anticipation of the start of the " Kotlin Backend Developer" course , we invite everyone to sign up for an open lesson on the topic "Kotlin multiplatform: front / back in one language" .
And now we offer you the traditional translation of the article for reading.
Today we are happy to announce the release of version 1.4.0 of the Kotlin Coroutines library. The major innovations in this release are StateFlow and SharedFlow , which are now stable APIs. StateFlow and SharedFlow are intended for use when state management is required in the context of asynchronous execution using Kotlin Coroutines.
API- Flow Kotlin , . , Flow โ . Kotlin Flow , Sequences: , , . . Sequences Flow Kotlin , Flow .
Flow : , API- Flow. Flow backpressure, โ .
val flow: Flow<Int> = flow {
delay(100)
for(i in 1..10) {
emit(i)
}
}.map {
delay(100)
it * it
}
Flow , Sequences. Flow , backpressure.
Flow API-, , . , . : , ยซยป ยซยป, ยซยป ยซยป. : .
API- Flow , . ConflatedBroadcastChannel. ConflatedBroadcastChannel . , , . , . , - !
ConflatedBroadcastChannel API- โ StateFlow SharedFlow!
StateFlow
StateFlow : StateFlow MutableStateFlow:
public interface StateFlow<out T> : SharedFlow<T> {
public val value: T
}
public interface MutableStateFlow<out T>: StateFlow<T>, MutableSharedFlow<T> {
public override var value: T
public fun compareAndSet(expect: T, update: T): Boolean
}
. .
, API-.
class DownloadingModel {
private val _state.value = MutableStateFlow<DownloadStatus>(DownloadStatus.NOT_REQUESTED)
val state: StateFlow<DownloadStatus> get() = _state
suspend fun download() {
_state.value = DownloadStatus.INITIALIZED
initializeConnection()
processAvailableContent {
partialData: ByteArray,
downloadedBytes: Long,
totalBytes: Long
->
storePartialData(partialData)
_state = DownloadProgress(downloadedBytes.toDouble() / totalBytes)
}
_state.value = DownloadStatus.SUCCESS
}
}
state, (state) . : state.value = DownloadStatus.INITIALIZED
. , , . , state
, .
, API . , - . , , state
Flow.
SharedFlow
, , ? API- SharedFlow. API- , .
public interface SharedFlow<out T> : Flow<T> {
public val replayCache: List<T>
}
โ , , . , .
SharedFlow MutableSharedFlow.
interface MutableSharedFlow<T> : SharedFlow<T>, FlowCollector<T> {
suspend fun emit(value: T)
fun tryEmit(value: T): Boolean
val subscriptionCount: StateFlow<Int>
fun resetReplayCache()
}
MutableSharedFlow . , MutableSharedFlow . , .
MutableSharedFlow . SharedFlow.
public fun <T> MutableSharedFlow(
replay: Int,
extraBufferCapacity: Int = 0,
onBufferOverflow: BufferOverflow = BufferOverflow.SUSPEND
): MutableSharedFlow<T>
MutableSharedFlow , , , , , . , , .
, Flow.shareIn
.
public fun <T> Flow<T>.shareIn(
scope: CoroutineScope,
replay: Int,
started: SharingStarted = SharingStarted.Eagerly
)
API- StateFlow SharedFlow Kotlin . , .
Kotlin Coroutines , Kotlin 1.4 Online Event.
"Kotlin Backend Developer".
"Kotlin multiplatform: front/back ".