CLOVIS
08/15/2021, 9:29 AMval cache = HashMap<Id, Deferred<Value>>()
val lock = Semaphore(1)
val cacheJob = SupervisorJob()
val cacheScope = CoroutineScope(cacheJob)
suspend fun get(id: Id) {
val r = lock.withPermit {
if (cache[id] == null) {
val c = CompletableDeferred()
cacheScope.launch {
c.complete(getElementFromNetwork(id))
}
c
} else cache[id]
}
r.await()
}
I think that's generally safe, but I'm not sure if it will correctly handle all cases (the ID is invalid, ...)Didier Villevalois
08/17/2021, 12:33 PMonReceive: SelectClause1<Message>
and onSend: SelectClause2<Message, SendSocket>
similar to the ones of the Channel
API.
Searching in this channel, I found:
1. some helpers to build select clauses https://gist.github.com/zach-klippenstein/fa4366388295282fa409c5085abada23 by @Zach Klippenstein (he/him) [MOD], however it seems to me that there are made to work with event callbacks,
2. a suggestion by @Matej Drobnič to use something like async { mySuspendFunction() }.onAwait
, however I can't seem to build a proper SelectClause1
with this.
As ZeroMQ uses a polling mechanism, I don't quite figure out how to use either of these solutions. Also, the AbstractChannel
code is quite overwhelming. Is there a paper/article discussing the possible SelectClause
implementations somewhere? Do anyone of you have some hints or advices to give me? Thanks in advance!Huan
08/17/2021, 1:36 PMtrySend
(experimental API). Could someone tell me what is the best choice?ursus
08/18/2021, 11:55 AMNon-fatal Exception: kotlinx.coroutines.flow.internal.ChildCancelledException: Child of the scoped flow was cancelled
Non-fatal Exception: kotlinx.coroutines.JobCancellationException: Job was cancelled
and no stacktrace; are there supposed to be ignored?aidanvii
08/19/2021, 1:59 PMResult
as a return type as of Kotlin 1.5. I’m having seemingly random crashes with suspending functions that return Result
(I haven’t checked with other inline/value classes). it’s happening in the generated invokeSuspend
:
Fatal Exception: java.lang.ClassCastException
java.util.ArrayList cannot be cast to kotlin.Result
I don’t have reliable repro steps for it, it seems to happen on some android devices, at different places but all the same crash, but not always 😢
I’m really stumped with it. I’ve been looking at the difference in the decompiled bytecode between suspending and non suspending functions that return Result
, I can see casting of some Object
to Result
, assuming that’s what’s failing 😕liminal
08/19/2021, 10:07 PMFlorian
08/20/2021, 5:21 PMdelay
to take longer than the specified time?
And do you think this will work to get the actual passed time after a delay (for example for a countdown timer)?
val timeBefore = SystemClock.elapsedRealtime()
delay(TICK_DELAY)
val timeAfter = SystemClock.elapsedRealtime()
val passedTime = timeAfter - timeBefore
Johnjake Talledo
08/21/2021, 9:39 AMSharedFlows
shareIn
in github or gitlab, I couldn't find good resources or articles with a sample. What I am trying to achieve is combine(flow1, flow2) with shareIn
, so I only need to getfetch
once and share this to at least 3 fragments. I really appreciate if someone could help. Best Regards to all.Didier Villevalois
08/22/2021, 12:27 PMSendChannel<E>.sendCatching(e: E): ChannelResult<Unit>
like there is a ReceiveChannel<E>.receiveCatching(): ChannelResult<E>
?Stylianos Gakis
08/22/2021, 4:06 PMcoroutineScope
inside a flow operator? I have a flow I’m mapping on, and I want, depending on the value do some multiple suspending calls that I would optimally prefer to be done in parallel. Specific example inside the thread 🧵Marty Pitt
08/23/2021, 8:14 AMsuspend fun
magnumrocha
08/23/2021, 2:50 PMcommonTest
, androidTest
, iosTest
) ? how to deal with Coroutine Context?Patrick Ramsey
08/23/2021, 11:10 PMCLOVIS
08/24/2021, 10:17 AMJob
or a CoroutineScope
?
So far I've been adding Job
parameters, but then I have to declare another CoroutineScope
field per class.K Merle
08/24/2021, 10:57 AMviewModelScope
or inside compose function with side-effect with compose?stojan
08/24/2021, 1:20 PMCoroutineScope
instead of a Job
? I need to launch a few suspend functions, and cancel them if a) the parent scope is canceled b) the VH scope is canceled (whatever comes first)Florian
08/24/2021, 6:37 PMlaunch
block around taskDao.increaseMillisCompletedToday
(which is a database operation) look dangerous? I use this to measure time but without the nested launch
, I think the length of the database operation itself is causing imprecision. The tick interval is every 1s.
fun startTimer() {
timerJob?.cancel()
timerJob = applicationScope.launch {
val selectedTask = selectedTask.first()
if (selectedTask != null) {
taskDao.updateLastActiveTimestamp(selectedTask.id, System.currentTimeMillis())
startTimerService()
timerRunningFlow.value = true
while (true) {
val timeBefore = SystemClock.elapsedRealtime()
delay(TICK_DELAY)
val timeAfter = SystemClock.elapsedRealtime()
val elapsedTime = timeAfter - timeBefore
launch {
taskDao.increaseMillisCompletedToday(selectedTask.id, elapsedTime)
}
}
}
}
}
Patrick Ramsey
08/25/2021, 1:58 AMfor (e in this) action(e)
— which looks like it’s implicitly calling this.iterator() and iterating over the channel that way. I assume that can’t actually be what’s happening (right?) since Iterator.next() is blocking. Or does Channel.consumeEach() actually block?Mickey Donaghy
08/25/2021, 8:49 AMJob
is there a way to find out where it was stuck? I can pass a CancellationException
in, but what I really want is a traceback for where it was when it got cancelled.Erik Dreyer
08/25/2021, 3:04 PM@PostMapping(path = ["/foo"])
suspend fun example(): Flow<String> {
val flux: Flux<String> = service.returnsFlux()
return flux // <-- how to convert to Flow?
}
(this is a trivial example, but I have an API that returns a FLux<T>
)
I’m trying to figure out how to go from a Mono/Flux
back to the kotlin coroutines approach for Spring Webflux.
I’d appreciate any help .Eric Ampire [MOD]
08/25/2021, 3:05 PMChris Fillmore
08/25/2021, 5:27 PMclass MyComponent {
private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
fun close() {
scope.cancel()
}
}
CoroutineScope with Dispatcher + Job:
class MyComponent {
private val job = Job()
private val scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + job)
fun close() {
job.cancel()
}
}
The second example is used e.g. in https://kenkyee.medium.com/android-kotlin-coroutine-best-practices-bc033fed62e7
I’m grateful for any insight! Thank you!Patrick Ramsey
08/25/2021, 9:33 PM@Test fun `some particular invariant holds true`() = runBlockingTest {
coEvery { someSuspendingFunction() } coAnswers {
val dispatcher = coroutineContext[CoroutineDispatcher]
....
}
....
}
No matter which CoroutineDispatcher someSuspendingFunction() was called on, dispatcher
in this code seems to end up being the test dispatcher created by runBlockingTest.
If, however, I structure it like this:
private suspend fun mockImplementation() {
val dispatcher = coroutineContext[CoroutineDispatcher]
}
@Test fun `some particular invariant holds true`() = runBlockingTest {
coEvery { someSuspendingFunction() } coAnswers {
mockImplementation()
}
}
dispatcher
(in mockImplementation()) matches the dispatcher that someSuspendingFunction() was called on.
IE… it looks an awful like the coAnswers block is running on that dispatcher, but coroutineContext
specifically inside that block is reporting something different. Put differently --- coroutineContext seems to be returning the context from the enclosing lexical scope, rather than the context of the actual running coroutine.
Is that expected?Scott Kruse
08/25/2021, 11:44 PMPatrick Ramsey
08/26/2021, 1:02 AMandylamax
08/26/2021, 2:59 AMprocess.nextTick is not a function. (In 'process.nextTick(this._get_messageQueue__1()._processQueue)', 'process.nextTick' is undefined)
at node_modules/@picortex/pi-monitor-client-sdk/pi-monitor-client-sdk.js:13160:17 in <anonymous>
Checking that line number, I see the following generated code
NodeDispatcher.prototype.scheduleQueueProcessing_1 = function () {
process.nextTick(this._get_messageQueue__1()._processQueue);
};
I think for some reasons, the library thinks it is running in a node environment. Is there a way I can make this work differently? Any work around?Scott Kruse
08/26/2021, 3:36 AMUnresolved reference: last
when referencing `
import kotlinx.coroutines.flow.last
from a unit test. Any ideas?Ananiya
08/26/2021, 9:15 AMinvokeOnCompletion
even after I surround it within coroutine
liveData {
val mainJob = viewModelScope.launch {
emit(Result.LOADING)
repo.add(data)
}
mainJob.join()
mainJob.invokeOnCompletion {
viewModelScope.launch {
if(it != null) emit(Result.FAILED(it) else emit(Result.SUCCESS(null)
}
}
}
Alternatively if I do
liveData {
val mainJob = viewModelScope.launch {
emit(Result.LOADING)
repo.add(data)
emit(Result.SUCCESS(null)
}
mainJob.join()
}
But I need to handle if it complete with in failure or successspierce7
08/26/2021, 5:00 PMThrowable
inside a coroutine with CancellationException?
I’m not relying on CancellationException
anywhere in code, and I don’t want it to show up in my logs. Should I just be watching for it and then re-throwing it, or is it acceptable to just eat it and not throw it?
} catch (e: CancellationException) {
throw e
} catch (t: Throwable) {
logger.w(RuntimeException("Error validating file", t))
count++
}
Vikas Singh
08/26/2021, 5:32 PMVikas Singh
08/26/2021, 5:32 PMNick Allen
08/26/2021, 5:44 PMdependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1'
}
There's others for interop with CompleteableFuture, RxJava, Android, and more.Vikas Singh
08/26/2021, 5:51 PMNick Allen
08/26/2021, 5:59 PMgradlew :app:dependencies
to see the full dependency tree. (assuming your module is :app
)Vikas Singh
08/26/2021, 6:34 PM