This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.flow.* | |
fun main() = runBlocking { | |
// Создаем MutableStateFlow с начальным состоянием "state1" | |
val mshState = MutableStateFlow("state1") | |
// Подписчик на изменения состояния | |
val job = launch { | |
mshState.collect { state -> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.flow.* | |
fun main() = runBlocking { | |
// Создаем SharedFlow | |
val shFlow = MutableSharedFlow<String>() | |
// Первый подписчик | |
val j1 = launch { | |
shFlow.collect { println("XX received: $it") } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.flow.* | |
fun main() = runBlocking { | |
// Создание простого потока | |
val flow = flow { | |
emit(1) | |
emit(2) | |
emit(3) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.channels.BufferOverflow | |
import kotlinx.coroutines.flow.* | |
import org.slf4j.LoggerFactory | |
fun main() = runBlocking { | |
val log = LoggerFactory.getLogger("FlowExample") | |
// Исходный поток | |
val flow = flow { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.channels.awaitClose | |
import kotlinx.coroutines.channels.trySendBlocking | |
import kotlinx.coroutines.flow.* | |
import java.util.Timer | |
import kotlin.concurrent.scheduleAtFixedRate | |
fun main(): Unit = runBlocking { | |
// 1. Пустой поток | |
println("Empty Flow:") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.flow.* | |
fun main(): Unit = runBlocking { // Запускаем основную корутину, которая блокирует главный поток. | |
val flow = flow<Int> { // Создаем поток данных (Flow) с типом элементов Int. | |
println("Started") // Выводим сообщение "Started" при каждом создании потока. | |
emit(1) // Эмитируем (выводим) значение 1 в поток. | |
} | |
// Запускаем первую корутину, которая будет собирать данные из потока. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
import kotlinx.coroutines.flow.* | |
suspend fun main() { // Главная функция, которая является корутиной и может выполнять асинхронные операции | |
withContext(Dispatchers.Default) { // Смена контекста на Default dispatcher для выполнения дальнейших операций | |
val result = flow { // Создаем Flow, который будет эмитировать элементы | |
println("Создание числа в потоке: ${Thread.currentThread().name}") // Выводим имя текущего потока | |
emit(10) // Эмиттируем число 10 в поток | |
} | |
.map { number -> // Применяем операцию map для каждого значения потока |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.flow.* | |
import kotlinx.coroutines.runBlocking | |
fun main() = runBlocking { | |
// (1) Билдер: создаем flow, который эмиттирует значения | |
flow<Int> { | |
emit(1) | |
emit(2) | |
emit(3) | |
emit(4) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.runBlocking | |
// Интерфейс Flow, представляющий поток данных | |
fun interface Flow<out T> { | |
// Метод для сбора данных из потока с использованием коллекторов | |
suspend fun collect(collector: FlowCollector<T>) | |
} | |
// Интерфейс FlowCollector, который собирает данные из потока | |
fun interface FlowCollector<in T> { |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlin.random.Random | |
fun main() { | |
// (1) Пустая последовательность | |
// Эта последовательность не содержит элементов и сразу завершает итерацию | |
val emptySeq = emptySequence<Int>() | |
println("Empty sequence: ${emptySeq.toList()}") // Печатает пустую последовательность | |
// (2) Из набора элементов | |
// Создаём последовательность из нескольких заранее заданных элементов |
NewerOlder