5,063 questions
Best practices
3
votes
0
replies
36
views
Testing with corroutines
Let's say I have Worker class and I want to do long running tasks in the background until user stops it or it is cancelled. It changes state of the class while doing the work and I want to write tests ...
3
votes
1
answer
91
views
Does combine conflate flows?
When I use combine() on two flow, it's not supposed to conflate/skip values. But when I collect a combine of 2 flows in a Coroutine, some values are randomly skipped.
Link to the kotlin playground : ...
0
votes
2
answers
58
views
Why is my continuous flow test code flaky?
I am trying to test the number of times a Flow is collected -
runTest {
var count = 0
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
dao.getEntities().collect {
...
4
votes
2
answers
152
views
How to call a composable function after a certain time in Jetpack Compose?
When my application starts, I launch an animation. Now I would like to switch to another component (navbar) after 30 seconds. In my research, I saw that the delay function from the Kotlin Coroutines ...
0
votes
0
answers
68
views
How does async exception propagation rally works?
I’ve read in multiple places that async can swallow exceptions if we don’t call await, but as far as I can see, it almost always throws them regardless of whether await is used or not.
For example, ...
0
votes
0
answers
27
views
Use suspend function with Vert.x Kafka Consumer?
I want to use suspend function in a handler for KafkaConsumer.
This is what I have so far, but I'm not sure about exception handling.
CoroutineEventBusSupport would call fail() on the message and ...
-2
votes
2
answers
122
views
Waiting for coroutine to end it's job to trigger an event [closed]
I have an Activity that is responsible for creating a new entry in the database. In this activity, a button launches a coroutine to do all the database-related stuff, and when it's done, navigate to ...
3
votes
0
answers
192
views
Objectify with Kotlin Ktor 3.3
Objectify v6.1.3
With Kotlin and Ktor 3.1, I was calling ObjectifyService.begin() within the init {} block of my request handler base class and then closing that context once the request was finished. ...
1
vote
1
answer
81
views
Differences between long-running Flow processing with transform() and flatMapLatest()
I have a data stream coming from the server. The server does not provide any information about when the next piece of data will arrive. I have a Flow in my repository that emits data as it arrives. ...
0
votes
3
answers
148
views
Are there any real difference between GlobalScope and CoroutineScope?
I'm trying to understand the difference between the 2.
If a CoroutineScope is not tied to any lifecycle-aware component, then I think they behave the same:
If Im not passing any context to ...
0
votes
1
answer
66
views
Is kotlin coroutine Job's status is reliable for concurrency control?
I've read this sentence in the Java Concurrency in Practice book that:
The result of Thread.getState should not be used for concurrency
control, and is of limited usefulness for testing—its primary ...
2
votes
1
answer
89
views
How can I tie a coroutine's lifetime to the lifetime of an object?
I have some code similar to this:
class Foo {
var x = 0
init {
GlobalScope.launch {
while (true) {
delay(1000)
x += 1
}...
0
votes
1
answer
166
views
Strictly depending on Coroutine 1.8.1 to use BroadcastChannel with Kotlin 2
I have a code base which is tightly coupled with BoradcastChannel and I can't update that for now. But I want to upgrade the dependencies to their latest, use kotlin2 and compose.
I have changed my ...
0
votes
1
answer
37
views
Creating activity prevents spinner from spinning in Android
I have 2 activities in my app. When another one is called there is a spinner but it doesn't spin. I think it may be because the main thread is stuck.
I moved all background tasks to Dispatchers.IO, ...
5
votes
0
answers
142
views
Why is the action of Mutex.withLock not marked as suspend?
The action parameter of the withLock function is a lambda without the suspend keyword. Is there a reason for this missing keyword?
In most cases, this lack of the suspend keyword isn't an issue ...
1
vote
2
answers
175
views
Testing a function that creates a coroutine scope inside it
I have something like the following in Kotlin:
class A {
fun a(): Unit = TODO()
}
fun foo(a: A) {
// Do something
CoroutineScope(Dispatchers.IO).launch {
delay(1000)
a.a()
...
2
votes
2
answers
101
views
Deadlock when withContext() is combined with logging in object initializer
Consider the following Kotlin object:
package com.example
import org.slf4j.LoggerFactory
import java.lang.Thread.currentThread
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines....
0
votes
1
answer
71
views
Jetpack Compose `LazyColumn takes` ~3 to ~4seconds to reflect `mutableStateListOf` mutations even though `Flow` emits immediately [closed]
I switch between “chart windows” (weekly, monthly…). Upstream data is a hot Flow (think Room).
To keep the list size stable, I render 30 fixed slots: real items in the first n, placeholders in the ...
2
votes
1
answer
65
views
Implement same task for two different user interfaces in Kotlin [closed]
I am working on a program which has both a TUI (terminal user interface) as well as a GUI (graphical user interface).
The program has some functions which take quite a long time to complete (waiting ...
0
votes
1
answer
98
views
Why does Android prohibit running IO-performing coroutines from the main thread? [closed]
Context and prior understanding:
In Node.JS, I/O code is run in a thread pool / event loop parallel to the main JavaScript thread. async code is never truly blocking per-se, unless a blocking call (e....
2
votes
1
answer
73
views
Unclear execution order of Kotlin coroutines
Why the output of this code is so unpredictable?
suspend fun main() {
val job1 = GlobalScope.launch {
delay(1000L)
println("World!")
}
val job2 = GlobalScope....
0
votes
1
answer
59
views
SharedFlow emmited in another scope in a separated class is not collected
I have a Bluetooth tracker app. I try it to be clean. Everything related to scan is encapsulated in one class. I am injecting with Hilt.
The problem is when I scan via Bluetooth for 10s, I emit the ...
0
votes
0
answers
42
views
Missing MDCContext from kotlin web flux
I have a spring web flux based application, written in kotlin I am adding few information in reactor context by using web filter. I also have logging information which I set in MDCContext but I am ...
0
votes
1
answer
101
views
Problems with Ktor receiving multipart: Flow invariant is violated
I am rather new to Ktor and try to upload a file to my server. This is the route:
fun Application.module() {
install(ContentNegotiation) {
json()
}
routing {
post("/upload") {
...
1
vote
1
answer
68
views
Why this code in Android onCreate is not Failing
So, I am aware of the fact that in Android, views cannot be updated from a background thread.
I have a TextView called appTitle.
I am launching a coroutine on background thread ( IO ) and on that ...
2
votes
1
answer
244
views
Kotlin' coroutines and retrofit2: Program blocks for one minute after getting http response
I need to use Kotlin' coroutines and the retrofit2 library to make http requests.
When I run the following code, the http request works as expected (posts is printed), but after this, the program ...
1
vote
1
answer
60
views
List of Stateflows not detecting changes
I am using the MVVM model and have come across a problem with Stateflow that I cannot find a solution. Perhaps I am approaching the problem in the wrong way.
Each of my Models responds to a specific ...
0
votes
1
answer
42
views
error handling and Structured concurrency in corutin
i have this code my viewmodel init
val scope = CoroutineScope(Dispatchers.Main )
var child1:Job = Job()
var child2 : Deferred<Unit> = CompletableDeferred(Unit)
child1 =scope....
1
vote
0
answers
122
views
Spring Security SecurityContext not propagating to Kotlin coroutines - getting UNAUTHORIZED
Problem
I'm using Spring Boot 3.3.3 with Spring Security and Kotlin coroutines. My authentication filter successfully authenticates the user and sets the SecurityContext, but when I use suspend fun in ...
0
votes
1
answer
111
views
Ktor/Exposed TransactionManager.currentOrNull() not null after closing newSuspendedTransaction block when block contains delay()
I’m looking for some insight into this issue I’m having with my Ktor/exposed application…
If I do the following in a KTOR route, after the newSuspendedTransaction block is closed, TransactionManager....
2
votes
2
answers
103
views
async await: Calling .await() on Deferred immediately - Correct?
These code is from a Udemy-course, which I'm following currently:
fun getWeatherData() {
viewModelScope.launch(exceptionHandler) {
uiState = try {
val ...
-1
votes
2
answers
160
views
Unit testing a broadcast receiver with callbackflow
I have the following class I am trying to test. I am using mockito as that is the library I am using
class ConsentUpdatedBroadcastReceiverImp @Inject constructor(
private val context: Context,
...
1
vote
1
answer
105
views
Using a flow to observe the onReceive of a broadcastreceiver and emit some value that can be observed
I have the following BroadCastReceiver. I inject a 3rd party library and have to call a method on it to get a result each time the onReceive is called. I need to observe this changes from our ...
1
vote
2
answers
221
views
How to unit test a withtimeout block
I have this block:
try {
withTimeout(200) {
val response = datafetcher.fetchData(request)
}
} catch (TimeoutCancellationException e) {
returns response with some error message added
}
I am ...
0
votes
1
answer
57
views
Room RawQuery in Compose: Cannot access database on the main thread. Need to return a Flow<List<MyEntity>>
I need to return a Flow<List<MyEntity<>> from Room @RawQuery in Compose but get runtime error: Cannot access database on the main thread.
I have found many posts for @Query about using ...
0
votes
1
answer
43
views
Why does this code crash when i am passing the scope created from viewmodelScope which is a supervisorScope?
// code inside viewModel
viewModelScope.launch(Dispatchers.IO) {
try {
tempUsecase.coroutineTest(
coroutineScope = this,
)
} catch (e: Exception) {
...
0
votes
1
answer
94
views
viewModelScope not working after Composable is revisited using Navigation in Jetpack Compose
So, i have a composable, a viewmodel and a repository. I am fetching data from Firebase's Firestore, and it already has some documents in the collection i am fetching from.
These are the snippets of:
...
1
vote
1
answer
79
views
How do you test code that uses withTimeout?
I have a code that uses withTimeout as follows.
suspend fun send(timeoutMillis: Long): Int? {
val result: Int? = withTimeoutOrNull(timeoutMillis) {
doSomething()
}
return result
}
suspend ...
0
votes
1
answer
22
views
SharedFlow builder
I have suspending function, which returns a hot flow.
suspend fun createFlow(): SharedFlow
How can I build another SharedFlow, which calls createFlow lazily (i.e. as only first subscriber connects to ...
2
votes
1
answer
193
views
Why is CoroutineContext element null via kotlin.coroutines.coroutineContext in tests (Kotest/Dispatchers.Default) but not production?
I'm encountering a discrepancy in retrieving a custom CoroutineContext.Element (TraceContextElement) depending on the environment (test vs. production) and how I access the context within a launched ...
3
votes
2
answers
282
views
How to spawn new coroutines for the processing of each element in a cold flow?
Came across an example that simulates accessing a slow database to obtain a flow of user identifiers which is associated with a profile that's accessible via an even slower network resource:
fun ...
0
votes
1
answer
75
views
Managing sequential callbacks with Kotlin
There is a very common pattern when dealing a remote service: A sequential series of calls to the service, each of which invokes a callback, asynchronously, when complete. I believe, for instance, ...
0
votes
2
answers
112
views
Android Jetpack Compose: How to stop execution of a coroutine launched in `produceState`?
Goal
I have a computation heavy function calculateItems: suspend (String) -> Sequence<String>.
I want to load the outputs of this calculation while showing the progress to the user and ...
0
votes
1
answer
279
views
How to update UI state using stateIn in ViewModel jetpack compose
I have a ProfileViewModel where I load the user profile when the user lands on the screen. To achieve this, I use stateIn so that the profile is fetched automatically.
Now, I want to modify ...
1
vote
1
answer
129
views
How to build list from async tasks properly in Kotlin
I have function like this
fun getUsersList(userIds: List<String>): List<User> {
val list = mutableListOf<User>()
userIds.forEach { id ->
getUserFromDatabase(id) {...
1
vote
0
answers
55
views
Some coroutines shenanigans in a custom flow operator with select clause
I have the following flow operator:
fun <T> Flow<T>.bufferedWithTimeout(
maxBufferSize: Int,
timeout: Duration
): Flow<List<T>> {
require(maxBufferSize > 0) {
&...
0
votes
1
answer
151
views
How to prevent coroutine scope cancellation on async failure without using a supervisorScope?
I’m working with a regular CoroutineScope (not a supervisorScope). I’ve noticed that when I launch an async block inside this scope, and it throws an exception—even if that exception is caught outside ...
1
vote
1
answer
97
views
ConflatedBufferedChannel onUndeliveredElement behavior
org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.1
ConflatedBufferedChannel with capacity = 1.
If onBufferOverflow is configured as BufferOverflow.DROP_OLDEST
trySend returns success.
...
2
votes
1
answer
50
views
Getting inconsistent results when using withTimeoutOrNull within small margins
Upon rerunning the following code, I am getting inconsistencies:
fun main(){
runBlocking{
withTimeoutOrNull(205){
delay(200)
println("Within Timeout")
...
0
votes
0
answers
44
views
Kotlin flow suspends in onEach for too long
I have a question about why my onEach intermediate operator suspends for so long? I have a web socket that emits a flow of events.
localJob = coroutineScope.async(Dispatchers.IO + ...