Last active
March 24, 2022 23:55
-
-
Save bananaumai/da23494ed2ba1d22c39af23a7c07ba2f to your computer and use it in GitHub Desktop.
Coroutines delay and Future get
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.Job | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.launch | |
import java.util.concurrent.CompletableFuture | |
fun main() { | |
val future = CompletableFuture<Unit>() | |
doSuspend { | |
println("called") | |
future.complete(Unit) | |
} | |
future.get() | |
println("complete") | |
} | |
fun doSuspend(callback: () -> Unit) { | |
CoroutineScope(Job()).launch { | |
println("call callback in 100ms") | |
delay(100) | |
println("call callback now") | |
callback() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.util.Log | |
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.Job | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.launch | |
import java.util.concurrent.CompletableFuture | |
class MainActivity : AppCompatActivity() { | |
companion object { | |
private const val TAG = "MainActivity" | |
} | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
val future = CompletableFuture<Unit>() | |
doSuspend { | |
Log.d(TAG, "called") | |
future.complete(Unit) | |
} | |
future.get() | |
Log.d(TAG, "complete") | |
} | |
private fun doSuspend(callback: () -> Unit) { | |
CoroutineScope(Job()).launch { | |
Log.d(TAG, "call callback in 100ms") | |
delay(100) | |
Log.d(TAG, "call callback now") | |
callback() | |
} | |
} | |
} |
This issue looks specific to coroutines v1.6.0. It's not reproduced with v1.5.3. Also this issue might be related the bug in 1.6.0 which could be fixed by this PR.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In Android code (MainActivity.kt), when doSuspend with future will block forever when get() is called. Particularly, inside doSuspend function,
delay
suspend function never completes.Meanwhile, on generic JVM environment, the same code can stop.