CLOVIS
04/17/2021, 12:41 PMSupervisorJob
, how can I stop all its children without an exception? If I use supervisorJob.cancel()
, an exception is thrown.Muhammad Usman
04/17/2021, 12:57 PMopen class RootResponse<T> {
var success: Boolean = false
var msg: String? = null
var data: T? = null
}
fun <E, T : RootResponse<E>> CoroutineScope.launchCatching(blk: suspend () -> T): Result<E> {
this.launch {
kotlin.runCatching { blk() }
.onSuccess {
if (it.success && it.data != null) {
Result.success(it.data)
} else {
Result.failure<String>(Throwable(it.msg))
}
}.onFailure {
Result.failure<String>(it)
}
}
}
Nowak
04/20/2021, 7:51 AMScott Kruse
04/20/2021, 4:43 PMFatal Exception: java.lang.StackOverflowError: stack size 8MB
at kotlin.Result$Failure.<init>()
at kotlin.ResultKt.createFailure(Result.kt:121)
at kotlinx.coroutines.DebugStringsKt.toDebugString(DebugStrings.kt:18)
at kotlinx.coroutines.internal.DispatchedContinuation.toString(DispatchedContinuation.kt:251)
at kotlinx.coroutines.DebugStringsKt.toDebugString(DebugStrings.kt:16)
at kotlinx.coroutines.CancellableContinuationImpl.toString(CancellableContinuationImpl.kt:506)
at java.lang.String.valueOf(String.java:2827)
at java.lang.StringBuilder.append(StringBuilder.java:132)
at kotlinx.coroutines.ResumeAwaitOnCompletion.toString(JobSupport.kt:1414)
ursus
04/21/2021, 12:04 AMsuspend fun BarcodeScanner.processSuspending(image: ImageProxy): Barcode? {
return suspendCancelableCoroutine { continuation ->
continuation.invokeOnCancelation {
this.clear()
}
this.process(image)
.addOnSuccessListener { barcodes ->
val barcode = barcodes.someTransformation()
continuation.resume(barcode)
}
.addOnFailure { throwable ->
continutaion.resumeWithException(throwable)
}
}
}
Would somebody mind looking at this if I do wrap a 3rd party callback library correctly? Its googles mlkit barcode scanner. Its my first time
Also, what is the best pragmatic name of providing a suspend function if the "native" is called process()
? processSuspending()
? or some sort of await
variant like awaitProcess()
?
Also2, I don't need to apply dispatcher, since it provides callbacks, meaning it most likely has its own thread inside, right?Patrick Ramsey
04/21/2021, 12:27 AMLilly
04/21/2021, 12:20 PMFlow
manually but also waits until all launched coroutines in this flow have finished? I have a channel which is receivedAsFlow
which in turn keeps the flow running until the channel is closed (by user or by exception). I would like to escape from this flow but also wait until all coroutines have finished...Kristian Frøhlich
04/21/2021, 12:44 PMErik
04/21/2021, 4:07 PMflow
and a suspending function foo
that I want to combine: when either produces a value, I want to combine the latest from both into a new emission. combine
does that for flows, but foo
is a suspending function that should be invoked only once. Also, combine
doesn't emit until both sources have emitted at least once, but I want to emit either value as soon as it arrives and only start combining when both sources have produced a value. The type of the flow emissions and the return type of the suspending function are equal. I can think of some ways to do this, but there might be a very idiomatic and logical way, or even standard way of doing this. Any idea?Erik
04/21/2021, 7:08 PMGetting value
tick 100
tick 200
0
tick 300
tick 400
1
Got value
tick 500
tick 600
A2
tick 700
tick 800
A3
tick 900
tick 1000
A4
The desired output
Getting value
tick 100
tick 200
0
tick 300
tick 400
1
Got value
A1 // <-- immediately emit and combine the value and the last emission from the upstream flow
tick 500
tick 600
A2
tick 700
tick 800
A3
tick 900
tick 1000
A4
Michal Klimczak
04/22/2021, 11:54 AMorg.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2-native-mt
in deps, but my Kotlin Native code doesn't have access to runBlocking. Docs seems to say it should be there: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html. I also tried adding these to iosTest
and it didn't work:
• org.jetbrains.kotlinx:kotlinx-coroutines-core-native:1.4.2-native-mt
• org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.4.2-native-mt
Heikki Rauhala
04/22/2021, 12:20 PMNote that the latest element is not emitted if it does not fit into the sampling window.mean in the documentation of
Flow.sample
? https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/sample.html
How can an element not fit in a sampling window? There will always be the next window, right? Unless the sampling is cancelled while there are un-emitted events in the latest window, but are there other situations where the latest event is not emitted?Filip Wiesner
04/22/2021, 6:54 PMSupervisorJob
(viewModelScope) throws exception?
My use case is that when debugging I want my app to crash whenever there is unhandled exception anywhere in my business logic but because viewModelScope
is SupervisorJob
, the coroutine is only getting cancelled.
This behavior can be achieved by using Dispatchers.Main
as context (presumably because it calls android UncaughtExceptionHandler
) but I how can I achieve this when using .Default
or .IO
dispatchers?pablisco
04/23/2021, 9:32 AMgenerateSequence
however it doesn’t support suspend operations 🙃
Anyone knows of an alternative for such case?Martyna Maron
04/23/2021, 12:21 PMmain
never returns 😕 All I need is for printSomethingWithDelay
to execute on a background thread, with no new coroutine, how can I achieve that?
fun main() {
runBlocking {
printSomethingWithDelay("something")
}
print("finished")
}
suspend fun printSomethingWithDelay(something: String) = withContext(AppDispatcher.appDispatcher){
delay(1000)
println(something)
}
object AppDispatcher {
val appDispatcher = Executors.newFixedThreadPool(1).asCoroutineDispatcher()
}
Erik
04/23/2021, 2:41 PM@Synchronized fun foo()
that now is being refactored to be @Synchronized suspend fun foo()
(ℹ️ this is kotlin.jvm.Synchronized
). The synchronisation is still needed if I don't know the context in which this will be called, right? Is there a way to also get rid of the synchronisation? Can I change to a single threaded executor to ensure calls to this function happen sequentially? Or would I need a mutex? Or is it fine as-is? I'm asking because @Synchronized suspend fun foo()
looks a bit non-coroutinesque to me.Guilherme Lima Pereira
04/23/2021, 3:44 PMDeferred
, launched on MainScope
, should I be able to await
until it finishes? I mean, should it block the Main Thread
(that’s my goal, even though it sounds weird)?Helio
04/25/2021, 2:55 AM1.4.10 -> 1.4.32
and Ktor 1.4.2 -> 1.5.3
. I was definitely expecting some of Unit tests to break due to compatibility and I’ve already fixed them. However, there are still 4 of them that I’m struggling to understand what could be wrong.
When one of the unit tests starts, it adds an entity to a Global Variable with type mutableListOf<MyModel>()
. I can confirm that the value was added successfully. ArrayList@XXXX
. However, when one of the routes of my Ktor server attempt to read the value from that Global Variable, it is empty and the id of the object is now ArrayList@YYYY
. It looks like when embeddedServer(…).start()
is executed, it creates a new instance of the Global Object, hence it is empty.
I’ve already tried many things, SynchronizeListOf, add the global variable into an object, but no matter what I do the reference of the GlobalObject into Ktor is always different.
Would anyone be able to shed some light, please?
Thanks heaps.christophsturm
04/25/2021, 6:32 PMGlobalScope.launch(Dispatchers.Unconfined) {
coroutineScope {
...
}
}
a good way to use structured concurrency in an async handler that does not know about coroutines?Bilagi
04/26/2021, 4:00 PMmzgreen
04/26/2021, 5:11 PMConor Fennell
04/26/2021, 9:36 PMio.prometheus.client.Counter
The prometheus Counter is a Java library.
Is there any concurrency issues people would foresee?
The prometheus implementation uses Compare and Swap operations so should be coroutine safe.
But saying that, there is a thread hash code used for some accounting ThreadLocal()
.
static final ThreadLocal<int[]> threadHashCode = new ThreadLocal();
static final Random rng = new Random();
static final int NCPU = Runtime.getRuntime().availableProcessors();
transient volatile Striped64.Cell[] cells;
transient volatile long base;
transient volatile int busy;
private static final AtomicLongFieldUpdater<Striped64> CAS_BASE = AtomicLongFieldUpdater.newUpdater(Striped64.class, "base");
private static final AtomicIntegerFieldUpdater<Striped64> CAS_BUSY = AtomicIntegerFieldUpdater.newUpdater(Striped64.class, "busy");
Zach Klippenstein (he/him) [MOD]
04/26/2021, 11:30 PMSlackbot
04/27/2021, 11:58 AMLilly
04/27/2021, 7:48 PMDerek Ellis
04/27/2021, 10:16 PMsealed class Update {
object Success : Update()
data class Progress(val message: String) : Update()
data class Failure(val throwable: Throwable) : Update()
}
Success
and Failure
emissions are collected, but Progress
ones are not
applying only two operators:
.filterNotNull()
.transformWhile { update ->
emit(update)
update !is Update.Failure && update !is Update.Success
}
I've debugged and logged everywhere I could, and the Progress
objects are definitely emitted by the flow, but they never make it to the .collect
. Am I missing something really obvious here?Norbi
04/28/2021, 11:53 AM// This is my asynchronous/suspending input stream
interface AsyncInputStream {
// This method has semantics similar to InputStream.read() but suspends instead of blocking
suspend fun read(): Int
}
fun AsyncInputStream.asInputStream() = object : java.io.InputStream() {
override fun read(): Int {
return runBlocking { this@asInputStream.read() } // Is runBlocking() correct here?
}
}
If I understand correctly, using runBlocking
is incorrect because it "should not be used from a coroutine", and AsyncInputStream.asInputStream()
would possibly be called from coroutines.
Thanks.gts13
04/28/2021, 3:00 PMdata class ViewItem(
val id: String,
val title: String,
var description: String = "" // yes a var
)
private val _items: MutableStateFlow<List<ViewItem>> = MutableStateFlow(emptyList())
val metrics: StateFlow<List<ViewItem>> = _metrics
_metrics.value = _metrics.value.toMutableList().find { // some predicate }?.description = "a new title"
The _metrics
won’t emit the new value (which is actually a change in the ViewItem
object.
Am I right or I am missing something here?
And If I am right, in order to solve the above “issue” I need to use Channel
or is there any other way with StateFlow
?Satyam Agarwal
04/28/2021, 8:00 PMGlobalScope.launch { … }
I read this article https://elizarov.medium.com/the-reason-to-avoid-globalscope-835337445abc which makes sense, and I almost always use withContext(AppropriateDispatcher) { … }
to offload heavy jobs.
I have a ktor server that receives around 260 req/sec and logs request and responses while receiving and responding, along with actual response.
This is done via an interceptor. Now I don’t care much about logging, so I was thinking to do something like GlobalScope.launch(MDCContext()) { interceptor.request.log(...) }
so that logging is eventually done, but the interceptor can proceed()
immediately.
In fact, I was thinking to do this to pretty much every logging,
Do you think it is a good way of doing the intention. What can be the consequences in regards to threads and CPU if a lot of logging suddenly starts offloading to GlobalScope ?
Anyone can help me as well 🙂 Any and all feedback is much appreciated.ursus
04/29/2021, 3:09 AMclass Foo(coroutineScope) {
fun bar() {
coroutineScope.launch {
...
}
}
}
This however does not compose as its not s suspend function 😑
What to do if a blocking function is needed for some legacy component?
If it were a suspend function, that legacy component might call it from within a runBlocking block
If however its a plain function, now I need to add a barBlocking as well to the api, which is ..ughh, not scaling wellursus
04/29/2021, 3:09 AMclass Foo(coroutineScope) {
fun bar() {
coroutineScope.launch {
...
}
}
}
This however does not compose as its not s suspend function 😑
What to do if a blocking function is needed for some legacy component?
If it were a suspend function, that legacy component might call it from within a runBlocking block
If however its a plain function, now I need to add a barBlocking as well to the api, which is ..ughh, not scaling wellstreetsofboston
04/29/2021, 4:02 AMuli
04/29/2021, 7:35 AMto keep the suspend functions running no matter the ui
This however does not compose
. What is your issue with the non-suspending approach?ursus
04/29/2021, 7:47 AMfun FirebaseMessagingService.onMessageReceived() {
runBlocking { thingThatWouldBeLaunchedInFoo() }
}