Questions tagged [kotlin-coroutines]
A language feature and a library introduced in Kotlin 1.3 that is used to implement the "green threads" model. It allows writing non-blocking IO code in a natural way, without resorting to futures or callbacks.
kotlin-coroutines
4,988
questions
309
votes
10
answers
243k
views
What does the suspend function mean in a Kotlin Coroutine?
I'm reading Kotlin Coroutine and know that it is based on suspend function. But what does suspend mean?
Can Coroutine or function get suspended?
From https://kotlinlang.org/docs/reference/coroutines....
281
votes
8
answers
87k
views
What is the difference between launch/join and async/await in Kotlin coroutines
In the kotlinx.coroutines library you can start new coroutine using either launch (with join) or async (with await). What is the difference between them?
261
votes
11
answers
105k
views
How to make "inappropriate blocking method call" appropriate?
I am currently trying to leverage kotlin coroutines more. But I face a problem: when using moshi or okhttp inside these coroutines I get a warning:
"inappropriate blocking method call"
What is the ...
245
votes
19
answers
222k
views
The AsyncTask API is deprecated in Android 11. What are the alternatives?
Google is deprecating Android AsyncTask API in Android 11 and suggesting to use java.util.concurrent instead. you can check out the commit here
*
* @deprecated Use the standard <code>java.util....
183
votes
9
answers
77k
views
MutableLiveData: Cannot invoke setValue on a background thread from Coroutine
I'm trying to trigger an update on LiveData from a coroutine:
object AddressList: MutableLiveData<List<Address>>()
fun getAddressesLiveData(): LiveData<List<Address>> {
...
132
votes
3
answers
41k
views
Kotlin: withContext() vs Async-await
I have been reading kotlin docs, and if I understood correctly the two Kotlin functions work as follows :
withContext(context): switches the context of the current coroutine, when the given block ...
119
votes
4
answers
59k
views
GlobalScope vs CoroutineScope vs lifecycleScope
I am used to working with AsyncTask and understand it pretty well due to its simplicity. But Coroutines are confusing to me. Can you please explain to me in a simple way what is the difference and ...
118
votes
3
answers
35k
views
Difference between a thread and a coroutine in Kotlin
Is there a specific language implementation in Kotlin which differs from another language's implementation of coroutines?
What does it mean that a coroutine is like a lightweight thread?
What is the ...
117
votes
7
answers
45k
views
Coroutines: runBlocking vs coroutineScope
I was reading Coroutine Basics trying to understand and learn it.
There is a part there with this code:
fun main() = runBlocking { // this: CoroutineScope
launch {
delay(200L)
...
112
votes
3
answers
36k
views
Existing 3-function callback to Kotlin Coroutines
I have a general question with a specific example: I'd like to use Kotlin coroutine magic instead of callback hell in Android when taking a picture.
manager.openCamera(cameraId, object : ...
104
votes
26
answers
86k
views
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution > java.lang.reflect.InvocationTargetException (no error message)
Android studio gave the error:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect....
102
votes
5
answers
58k
views
Kotlin Flow vs Android LiveData
I have some questions about Kotlin Flow
I can observe LiveData from multiple Fragments. Can I do this with Flow? If yes then how?
We can have multiple LiveData from a single LiveData using map& ...
99
votes
4
answers
56k
views
Call Kotlin suspend function in Java class
Assume we have the following suspend function:
suspend fun doSomething(): List<MyClass> { ... }
If I want to call this function in one of my existing Java classes (which I'm not able to ...
95
votes
9
answers
84k
views
Implementing coroutines in Java
This question is related to my question on existing coroutine implementations in Java. If, as I suspect, it turns out that there is no full implementation of coroutines currently available in Java, ...
94
votes
3
answers
30k
views
Kotlin: Coroutines scope vs Coroutine context
Can anyone explain the difference between them? I think scope provides a reference(e.g. Job) to cancel them and context provides a reference to underlying thread. Is that so?
92
votes
1
answer
11k
views
Can "experimental" Kotlin coroutines be used in production?
Can Kotlin coroutines be used in production, and what does their experimental status mean?
87
votes
3
answers
26k
views
Kotlin Coroutines: Channel vs Flow
I'm recently studying and reading a lot about Flow and Kotlin Coroutines. But I still get confused about when I should use Flow and when I should use Channel.
At the beginning it looked more simple. ...
86
votes
11
answers
74k
views
Kotlin Flow: How to unsubscribe/stop
Update Coroutines 1.3.0-RC
Working version:
@FlowPreview
suspend fun streamTest(): Flow<String> = channelFlow {
listener.onSomeResult { result ->
if (!isClosedForSend) {
...
82
votes
2
answers
44k
views
Difference between usage of Dispatcher IO and Default
In this question: Kotlin Coroutines choosing Dispatcher
we can understand to use Dispatcher.Default on CPU process, like an image/video conversion and Dispatcher.IO when writing/reading files or API ...
81
votes
7
answers
125k
views
Kotlin Coroutines with returning value
I want to create a coroutine method which has returning value.
For example)
fun funA() = async(CommonPool) {
return 1
}
fun funB() = async(CommonPool) {
return 2
}
fun sum() {
launch {
...
76
votes
16
answers
66k
views
Kotlin Android debounce
Is there any fancy way to implement debounce logic with Kotlin Android?
I'm not using Rx in project.
There is a way in Java, but it is too big as for me here.
76
votes
3
answers
93k
views
Suspend function 'callGetApi' should be called only from a coroutine or another suspend function
I am calling suspended function from onCreate(...)
override fun onCreate(savedInstanceState: Bundle?) {
...
...
callGetApi()
}
and the suspended function is:-
suspend fun callGetApi() {....
75
votes
8
answers
35k
views
Using rememberCoroutineScope() vs LaunchedEffect
Context
In Jetpack compose, we have the option of using rememberCoroutineScope() as well as using the LaunchedEffect composable in order to use coroutines / run suspend functions (show snackbars etc).
...
74
votes
13
answers
91k
views
How to implement timer with Kotlin coroutines
I want to implement timer using Kotlin coroutines, something similar to this implemented with RxJava:
Flowable.interval(0, 5, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers....
69
votes
10
answers
41k
views
Unit testing coroutines runBlockingTest: This job has not completed yet
Please find below a function using a coroutine to replace callback :
override suspend fun signUp(authentication: Authentication): AuthenticationError {
return suspendCancellableCoroutine {
...
65
votes
9
answers
53k
views
Unresolved reference: launch
Trying to run some examples for Kotlin coroutines, but can't build my project. I'm using the latest gradle release - 4.1
Any suggestions what to check/fix?
Here is build.gradle
buildscript {
...
64
votes
2
answers
39k
views
Run two Kotlin coroutines inside coroutine in parallel
I have two suspend functions:
suspend fun sendData() : Boolean
suspend fun awaitAcknowledge() : Boolean
and I want to wrap them in a third suspend function in which they should be executed in ...
63
votes
8
answers
50k
views
Kotlin coroutine unit test fails with "Module with the Main dispatcher had failed to initialize"
While running unit test for kotlin suspend method which uses withContext(Dispatchers.Main) the test method fails with below exception:
My coroutine lib versions are kotlinx-coroutines-core:1.1.1 and ...
63
votes
1
answer
21k
views
how to pass suspend function as parameter to another function? Kotlin Coroutines
I want to send suspending function as a parameter, but it shows " Modifier 'suspend' is not applicable to 'value parameter" . how to do it?
fun MyModel.onBG(suspend bar: () -> Unit) {
launch {
...
63
votes
1
answer
28k
views
Laggy Lazy Column Android Compose
I've created a whole app in Jetpack Compose. However, the performances on the Lazy Column are pretty bad and it does not make any sense. Lazy Column should be the substitution of RecyclerView, but ...
62
votes
3
answers
63k
views
How to call Kotlin coroutine in composable function callbacks?
I want to call a suspend-function inside of a callback of composable-function.
suspend fun getLocation(): Location? { /* ... */ }
@Composable
fun F() {
val (location, setLocation) = remember { ...
62
votes
2
answers
18k
views
How do Kotlin coroutines work internally?
How does Kotlin implement coroutines internally?
Coroutines are said to be a "lighter version" of threads, and I understand that they use threads internally to execute coroutines.
What ...
61
votes
6
answers
35k
views
How to Exponential Backoff retry on kotlin coroutines
I am using kotlin coroutines for network request using extension method to call class in retrofit like this
public suspend fun <T : Any> Call<T>.await(): T {
return ...
60
votes
1
answer
17k
views
Which of coroutines (goroutines and kotlin coroutines) are faster? [closed]
Kotlin corutines is sugar for finite state machine and some task runner (for example, default ForkJoinPool). https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#...
59
votes
14
answers
45k
views
Unresolved reference: viewModelScope - Kotlin Android
I try to add viewModelScope to a basic viewModel but android studio doesn't recognize it.
I tried to change my gradle build file with some solution I found but nothing works.
Here an extract of my ...
57
votes
4
answers
28k
views
Handle exceptions thrown by a custom okhttp Interceptor in Kotlin Coroutines
I'm using a custom Interceptor along with Retrofit client in my Android app, that throws an Exception under some specific circumstances. I'm trying to make it work using Kotlin coroutines.
The ...
56
votes
2
answers
45k
views
Kotlin coroutines `runBlocking`
I am learning Kotlin coroutines. I've read that runBlocking is the way to bridge synchronous and asynchronous code. But what is the performance gain if the runBlocking stops the UI thread?
For ...
55
votes
4
answers
43k
views
Why not use GlobalScope.launch?
I read that usage of Globalscope is highly discouraged, here.
I have a simple use-case. For every kafka message (let's say a list of Ids) that I receive I have to split it and invoke a rest service ...
54
votes
5
answers
23k
views
How to handle 204 response in Retrofit using Kotlin Coroutines?
I'm using Retrofit 2.7.1 with Kotlin coroutines.
I have a Retrofit service defined as such:
@PUT("/users/{userId}.json")
suspend fun updateUserProfile(
@Path("userId") userId: String,
...
53
votes
11
answers
111k
views
AsyncTask in Android with Kotlin
How to make an API call in Android with Kotlin?
I have heard of Anko . But I want to use methods provided by Kotlin like in Android we have Asynctask for background operations.
52
votes
10
answers
60k
views
MutableStateFlow is not emitting values after 1st emit kotlin coroutine
This is my FirebaseOTPVerificationOperation class, where my MutableStateFlow properties are defined, and values are changed,
@ExperimentalCoroutinesApi
class FirebaseOTPVerificationOperation @...
51
votes
1
answer
13k
views
kotlin coroutines, what is the difference between coroutineScope and withContext
withContext
suspend fun <T> withContext(
context: CoroutineContext,
block: suspend CoroutineScope.() -> T
): T (source)
Calls the specified suspending block with a given coroutine ...
50
votes
5
answers
17k
views
When to use coroutineScope vs supervisorScope?
Can someone explain what exactly is the difference between these two?
When do you use one over the other?
Thanks in advance.
49
votes
4
answers
38k
views
java.lang.IllegalStateException when using State in Android Jetpack Compose
I have ViewModel with Kotlin sealed class to provide different states for UI. Also, I use androidx.compose.runtime.State object to notify UI about changes in state.
If error on MyApi request occurs, I ...
49
votes
4
answers
43k
views
Unit testing a Kotlin coroutine with delay
I'm trying to unit test a Kotlin coroutine that uses delay(). For the unit test I don't care about the delay(), it's just slowing the test down. I'd like to run the test in some way that doesn't ...
48
votes
5
answers
28k
views
Coroutine scope on Application class android
I need a reference to coroutine scope on my android Application. i did the following
class TodoApplication : Application() {
private var job = Job()
private val applicationScope = ...
48
votes
2
answers
16k
views
Understanding Kotlin's yield function
I don't see a very clear definition of the yield function in Kotlin.
Example in the link above doesn't mention much but the following,
val sequence = sequence {
val start = 0
// yielding a ...
46
votes
3
answers
21k
views
How to use code that relies on ThreadLocal with Kotlin coroutines
Some JVM frameworks use ThreadLocal to store the call context of a application, like the SLF4j MDC, transaction managers, security managers, and others.
However, Kotlin coroutines are dispatched on ...
44
votes
3
answers
28k
views
Using kotlinx.coroutines in IntelliJ IDEA project
I am trying to learn coroutines and so I fire up IntelliJ and create a scratch file. But when I type in my coroutines I get compiler complaints such as runBlocking is an unresolved reference. So this ...
44
votes
3
answers
7k
views
Type mismatch inferred type is () -> Unit but FlowCollector<Int> was expected
When trying to collect from a Flow the type suddenly mismatches, and it was working and then started suddenly.
In my viewmodel:
class MyViewModel: ViewModel() {
lateinit var river: Flow<...