Dmitry Khalanskiy [JB]
12/17/2021, 7:25 AMFlow.collect
broken in RC2.
Full changelog: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.6.0-RC3Tower Guidev2
12/17/2021, 1:50 PMRemy Benza
12/17/2021, 5:24 PMasync { }
builder? Or does the performance large depends on the I/O speed of the UFS storage?Exerosis
12/18/2021, 4:22 PMvar resumePoint: Continuation<String>? = null
var hasJumpedBack = false
suspend fun test() = suspendCoroutineUninterceptedOrReturn<String> {
resumePoint = it
"Hello "
}
fun jumpBack() {
if (!hasJumpedBack) {
hasJumpedBack = true
resumePoint?.resume("World")
}
}
runBlocking {
println("Starting")
val result = test()
println(result)
jumpBack()
}
It had to be testedigor.wojda
12/20/2021, 7:54 AM// Run job that prints "ABC" string every 1000ms
val repeatJob = repeatJob(1000) { println("ABC") }
//until job is canceled
repeatJob?.cancel()
yschimke
12/20/2021, 9:56 AMPablo
12/20/2021, 11:40 AM.onCompletion
?
I have this flow :
flow {
for(foo in bar downTo 0){
emit(foo)
delay(1_000L)
}
}
Then I consume it :
myFlow()
.onEach {
updateUI
}
.onCompletion {
//Do something but only when the timer is 0 not when cancelled
}
.launchIn(scope)
In some point I do cancel the scope and it automatically get into `onCompletion` so even if the timer is not over yet, it does the thing of timer finished because I have the code there, is there any way I can get if the completion is because ok the for loop or for a cancellation of scope?
Javier
12/20/2021, 12:28 PMhttps://www.youtube.com/watch?v=9R1IdMwSVps▾
Alexandru Hadăr
12/21/2021, 12:28 PMbrabo-hi
12/21/2021, 9:56 PMVivek Sharma
12/22/2021, 12:45 PMscope.launch{ // doing some work here which is having loops }
I want to stop doing that work on button click
so I tried doing like this: job = scope.launch{ // doing some work here which is having loops }
and then canceling the job : job?.cancel
but it seems like loops are executing till termination and the job is not getting canceled
Any other workaround?Vsevolod Tolstopyatov [JB]
12/22/2021, 12:47 PMkotlinx-coroutines-test
module with reworked API and multiplatform support
• CoroutineDispatcher.limitedParallelism
and elastic <http://Dispathers.IO|Dispathers.IO>
• Out-of-the-box support of new K/N memory model
• CopyableThreadContextElement
for mutable context elements
• And a lot of improvements and bug fixes: https://github.com/Kotlin/kotlinx.coroutines/releases/tag/1.6.0
We also have a blogpost and what’s new▾
Storozh Kateryna
12/22/2021, 1:03 PMMaciek
12/22/2021, 2:09 PMcatch { }
in the chain? If I'd want to have a infinite flow I must handle the exceptions with try catch
in the lambdas because flow will close after any exception "leaking" to the stream, right? Or is there a way to do some explicit recovery from the exception? Example code: only 0
will be emitted, next emit 1
is never executed due to flow completion after exception.
flow {
emit(0)
emit(1) // never executed
}
.onEach { if (it == 0) throw Throwable() }
.catch { println(it) } // catch and ignore
.collect()
ursus
12/23/2021, 3:29 AMgotoOla
12/23/2021, 9:59 AMrkeazor
12/23/2021, 11:38 AMNo matching variant of org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0 was found. The consumer was configured to find an API of a platform, preferably optimized for Android, as well as attribute 'com.android.build.api.attributes.BuildTypeAttr' with value 'debug', attribute 'store' with value 'googleplay', attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm' but:
- Variant 'commonMainMetadataElements' capability org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0:
- Incompatible because this component declares a usage of 'kotlin-api' of a library, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'common' and the consumer needed an API of a platform, as well as attribute 'org.jetbrains.kotlin.platform.type' with value 'androidJvm'
zak.taccardi
12/23/2021, 8:18 PMoffer(..)
and trySend(..)
change?Doru N.
12/23/2021, 9:01 PMflow {
// The WRONG way to change context for CPU-consuming code in flow builder
withContext(Dispatchers.Default) {
for (i in 1..3) {
Thread.sleep(100) // pretend we are computing it in CPU-consuming way
emit(i) // emit next value
}
}
}
.onEach { value -> println(value) }
.launchIn(scope)
crashes with java.lang.IllegalStateException: Flow invariant is violated…,
but this one does not:
flowOf(1, 2, 3)
.transformLatest {
withContext(Dispatchers.Default) {
Thread.sleep(100) // pretend we are computing it in CPU-consuming way
println("emitting $it, on thread: ${Thread.currentThread().name}")
emit(it) // emit next value
}
}
.onEach {
println("collect.onEach: $it, on thread: ${Thread.currentThread().name}")
}
.launchIn(scope)
to me, it should be the same case as the first (should crash with same exception). What am I missing here?
logs for 2nd sample is this:
emitting 1, on thread: DefaultDispatcher-worker-1
collect.onEach: 1, on thread: main
emitting 3, on thread: DefaultDispatcher-worker-1
collect.onEach: 3, on thread: main
ursus
12/26/2021, 2:10 AMclass Presenter {
init {
presenterScope.launch {
syncer.syncingFinishedEvent
.collect {
navigateSomewhere()
}
}
syncer.sync()
}
}
class Syncer {
fun sync() {
syncerScope.launch {
...
syncFinishedEvent.emit(Unit)
}
}
}
Is there a way to only call syncer.sync()
after syncer.syncingFinishedEvent
is for sure subscribed to? I cannot miss a eventAnshulupadhyay03
12/26/2021, 6:36 PMprivate fun createConnection() {
val hostAdd = InetAddress.getByName(endpoint)
val connection = Socket(hostAdd, port)
this.socketConnection = connection
inputStream = DataInputStream(connection.inputStream)
outPutStream = DataOutputStream(connection.outputStream)
}
private fun sendStreamRequest(request: String) {
try {
outPutStream?.writeBytes(request)
outPutStream?.flush()
Log.d(tag, "sendStreamRequest $request")
} catch (ex: Exception) {
ex.printStackTrace()
}
}
The below is the methods subcribes for the updates via callback flow
override fun subscribe(request: String):Flow<String> = callbackFlow {
sendStreamRequest(requestFormatter.formatSubscribeRequest(request))
try {
inputStream?.bufferedReader().takeUnless {
it == null
}.use {
it?.forEachLine { response ->
Log.d(tag, "Streaming $response")
val result = trySend(response)//trySendBlocking(response)
Log.d(tag, "result ${result.isSuccess}")
}
}
} catch (ex: Exception) {
ex.printStackTrace()
}
awaitClose {
Log.d(tag, "awaitclose")
sendStreamRequest(requestFormatter.formatUnSubscribeRequest(request))
}
}
There are few problems that i see in the subscribe method
1. The whole code is written insider a singleton class so everytime i subscribe this code inputStream?.bufferedReader()
will create addition objects (Let me know if i am right)
2. if i move the code `inputStream?.bufferedReader()`out of the subscribe method how can i update the subscribber ?? Can i use the produdeScope i get from callback flow builder and call trySend method from outside?
3. I also want to listen for network connection changes if the connetion looses i will establish the connection again and let the subscribber listen the updates again but not sure how to do that.
Any guidance on this to improve would be of great help. I know listen streams using TCP may sound weird but it is a legacy code which i am trying to convert into Kotlin.Mitchell Syer
12/27/2021, 2:59 AMlimitedParallelism
api like this <http://Dispatchers.IO|Dispatchers.IO>.limitedParallelism(1)
, will the dispatcher always dispatch to the same thread?juliocbcotta
12/27/2021, 11:59 AMcatch { log(it) throw it}
? Something like doOnError
?Pablo
12/27/2021, 4:18 PMConstraintLayout
is it good to implement the CoroutineScope
? Or it's better to create a scope
private val scope = MainScope()
And use it and cancel it depending on if the view is visible or not (attached/detached). The thing is that I'm doing some things and painting the custom view so I'm using a CoroutineScope for this but I'm afraid that if the CustomView is gone the coroutine is not and then try to do something and crash the app. Have anyone of you faced something similar? I used to inject the lifecycle of the "parent" let's say an Activity
or a Fragment
and once this is gone the coroutine is cancelled automatically.ursus
12/28/2021, 1:53 AMCaio Costa
12/29/2021, 10:09 PMTim Malseed
12/30/2021, 11:08 AMrunBlockingTest()
, this delay is skipped, so this function completes immediately, and the StateFlow essentially bypasses the value I’m trying to test.
It’s worth mentioning, I’m using CashApp/Turbine as well.ursus
01/01/2022, 3:38 PMbuffer
or conflate
• Hot streams default behavior varies
• MutableSharedFlow is suspend by default but can modify this behavior in the ctor
• MutableStateFlow is conflated by default and you CANNOT modify this behavior
• In both hot streams, downstream CANNOT modify this behavior (i.e. buffer or conflate dont do anything)
Everything correct?
(Most importantly whether downstream is able buffer on backpressure from hot upstream)tseisel
01/01/2022, 9:04 PMclass SomeManager(
private val source: DataSource,
private val externalScope: CoroutineScope
) {
private val cache: SharedFlow<Foo> by lazy {
source.fooFlow.shareIn(externalScope, SharingStarted.EAGERLY, 1)
}
suspend fun readCached(): Foo {
return cache.first()
}
}
Why does the following test hangs forever? How can I test this kind of class that requires an external CoroutineScope ?
@Test fun test() = runTest {
val subject = SomeManager(someSource, this)
val cachedValue = subject.readCached()
assertEquals(expectedFoo, cachedValue)
// HANGS HERE - due to having at least one child coroutine?
}
Nacho Ruiz Martin
01/02/2022, 2:34 PMStateFlow
and still have a StateFlow
and not a Flow
?
stateflow.map(::mapper)
returns a Flow
.Nacho Ruiz Martin
01/02/2022, 2:34 PMStateFlow
and still have a StateFlow
and not a Flow
?
stateflow.map(::mapper)
returns a Flow
.Joffrey
01/02/2022, 2:36 PMStateFlow
you would need to store a new state and to have a coroutine that collects the source flow into the new one. You could use stateIn after map
to do that for you behind the scenes.Nacho Ruiz Martin
01/02/2022, 2:37 PMJoffrey
01/02/2022, 2:37 PMStateFlow
as a result there (why is Flow
not sufficient)?Nacho Ruiz Martin
01/02/2022, 2:41 PMStateFlow
just to have better integration with Jetpack Compose.
In Rx
a simple map
on a BehaviourSubject
would suffice, if I’m not mistaken.streetsofboston
01/02/2022, 2:49 PMmap
method on BehaviorSubject
is a plain Observable
(which is comparable to a plain Flow
), which gives you the same type of problem that you are asking about.
http://reactivex.io/RxJava/3.x/javadoc/io/reactivex/rxjava3/subjects/BehaviorSubject.htmlNacho Ruiz Martin
01/02/2022, 2:49 PMMartin Rajniak
01/02/2022, 2:58 PMAdam Powell
01/02/2022, 4:18 PMNacho Ruiz Martin
01/02/2022, 5:50 PMstateIn
. Feels a bit weird, but it works.hfhbd
01/02/2022, 10:51 PM(Mutable) State
is nice, the advantage using StateFlow
is multiplatform support, especially iOS.