Oqim ishga tushirilmoqda
Shuni ta'kidlash kerakki, qabul qilingan ma'lumotlarga terminal operatsiyasi qo'llanilmaguncha, asenkron ip ishlamaydi, masalan collect():
1
2018-05-01 xoxlasa buladi 121 2
3
4
5
6
7
sakkiz
to'qqiz
o'n
o'n bir
12
13
o'n to'rt
15
16
|
import kotlinx.coroutines.flow.*
suspend fun main(){
val numberFlow = getNumbers() // поток создан, но не запущен
println("numberFlow has created")
println("launch collect function")
numberFlow.collect { number -> println(number) } // запуск потока
}
fun getNumbers() = flow{
println("numberFlow has started")
for(item in 1..5){
emit(item * item)
}
}
|
Dasturning konsol chiqishi:
numberFlow yaratdi
yig'ish funktsiyasini ishga tushiring
numberFlow boshlandi
1
4
to'qqiz
16
25
Birinchi, oxirgi, yagona funktsiyalar
Usul first()ro'yxatning birinchi ob'ektini oladi:
1
2018-05-01 xoxlasa buladi 121 2
3
4
5
6
7
sakkiz
|
import kotlinx.coroutines.flow.*
suspend fun main(){
val userFlow = listOf("Tom", "Bob", "Kate", "Sam", "Alice").asFlow()
val firstUser = userFlow.first()
println("First User: $firstUser") // First User: Tom
}
|
Usul first(), shuningdek , mantiqiy ob'ektni qaytaradigan parametr sifatida shart funktsiyasini olishi mumkin. Keyin first() bu shartga mos keladigan oqimning birinchi elementini qaytaradi:
1
2018-05-01 xoxlasa buladi 121 2
3
4
5
6
7
sakkiz
|
import kotlinx.coroutines.flow.*
suspend fun main(){
val userFlow = listOf("Tom", "Bob", "Kate", "Sam", "Alice").asFlow()
val firstUser = userFlow.first{ name-> name.length > 3}
println("First User: $firstUser") // First User: Kate
}
|
Bu erda biz 3 belgidan ortiq uzunlikdagi birinchi elementni olamiz. Oqimda bu "Keyt" qatori.
Biroq, oqim elementlarining hech biri shartga javob bermasa, vaziyat yuzaga kelishi mumkin:
1
2018-05-01 xoxlasa buladi 121 2
|
val userFlow = listOf("Tom", "Bob", "Sam").asFlow()
val firstUser = userFlow.first{ name-> name.length > 3}
|
Yoki oqim juda bo'sh:
1
2018-05-01 xoxlasa buladi 121 2
|
val userFlow = listOf().asFlow()
val firstUser = userFlow.first()
|
Ikkala holatda ham dastur ishlayotganda istisno qilinadi. Bunday holda, biz istisnoni, albatta, ishlatishimiz mumkin try..catch. Biroq, muqobil sifatida, Kotlin oqim bo'sh bo'lsa yoki uning elementlaridan hech biri shartga mos kelmasa, firstOrNull()qaytaradigan usulni taqdim etadi null:
1
2018-05-01 xoxlasa buladi 121 2
3
|
val userFlow = listOf().asFlow()
val firstUser1 = userFlow.firstOrNull()
val firstUser2 = userFlow.firstOrNull{ name-> name.length > 3}
|
Bunday holda, biz natija qiymatini tekshirishimiz mumkin null:
1
2018-05-01 xoxlasa buladi 121 2
3
4
|
if(firstUser1 == null)
println("User not found")
else
println("First User: $firstUser1")
|
Do'stlaringiz bilan baham: |