kotlin-coroutines

How to cancel the blocking code in the coroutines

江枫思渺然 提交于 2019-12-11 05:32:48
问题 I have the following code structure: @Throws(InterruptedException::class) fun method() { // do some blocking operations like Thread.sleep(...) } var job = launch { method() } job.cancelAndJoin() The method is provided by the external library and I can't control its behaviour. It can take a lot of time for execution, so in some cases it should be canceled by timeout. I can use the withTimeout function provided by the kotlin coroutines library, but it can't cancel a code with blockings due to

How to unit test coroutine when it contains coroutine delay?

百般思念 提交于 2019-12-11 04:25:43
问题 When I add a coroutine delay() in my view model, the remaining part of the code will not be executed. This is my demo code: class SimpleViewModel : ViewModel(), CoroutineScope { override val coroutineContext: CoroutineContext get() = Dispatchers.Unconfined var data = 0 fun doSomething() { launch { delay(1000) data = 1 } } } class ScopedViewModelTest { @Test fun coroutineDelay() { // Arrange val viewModel = SimpleViewModel() // ActTes viewModel.doSomething() // Assert Assert.assertEquals(1,

How to run suspend method via reflection?

荒凉一梦 提交于 2019-12-11 02:21:29
问题 There is an coroutine block that can runs suspend functions. But I call the function by invoke via reflection. This is java style invocation, apparently a simple call will not work. Are there ways to run reflected method asynchronously? How to await this method? import kotlin.coroutines.experimental.* class TestClass(val InString: String) { suspend fun printString() { println(InString) } } fun launch(context: CoroutineContext, block: suspend () -> Unit) = block.startCoroutine

Is it ok to use sharedPrefrence with Coroutine kotlin

拟墨画扇 提交于 2019-12-10 23:09:25
问题 I have injected sharedPreference in ViewModel . Can I use android specific resource's while embedding Coroutine scope which automatically suspended when ViewModel loses scope. I mean is it ok to use preferende in ViewModel if we add a viewModel launch scope A CoroutineScope keeps track of all coroutines it creates. Therefore, if you cancel a scope, you cancel all coroutines it created @ContributesViewModel class SplashViewModel @Inject constructor(private val prefs: PrefStore) : BaseViewModel

Why does launch swallow exceptions in kotlin coroutines?

吃可爱长大的小学妹 提交于 2019-12-10 16:25:58
问题 The following test succeeds with Process finished with exit code 0 . Note, this test does print the exception to the logs, but does not fail the test (which is the behavior I want). @Test fun why_does_this_test_pass() { val job = launch(Unconfined) { throw IllegalStateException("why does this exception not fail the test?") } // because of `Unconfined` dispatcher, exception is thrown before test function completes } As expected, this test fails with Process finished with exit code 255 @Test

kotlin coroutines - use main thread in run blocking

时光怂恿深爱的人放手 提交于 2019-12-10 14:47:22
问题 I am trying to execute following code: val jobs = listOf(...) return runBlocking(CommonPool) { val executed = jobs.map { async { it.execute() } }.toTypedArray() awaitAll(*executed) } where jobs is the list of some Supplier s - in synchronus world this should just create, for example, list of ints. Everything works fine, but the problem is the main thread is not utilized. Bellow screenshot from YourKit: So, the question is - how can I utilize main thread also? I suppose runBlocking is the

Retrofit 2.6.0 exception: java.lang.IllegalArgumentException: Unable to create call adapter for kotlinx.coroutines.Deferred

老子叫甜甜 提交于 2019-12-10 12:47:05
问题 I have a project with Kotlin coroutines and Retrofit. I had these dependencies: implementation 'com.squareup.retrofit2:retrofit:2.5.0' implementation 'com.squareup.retrofit2:converter-gson:2.5.0' implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2' Today I have updated Retrofit to 2.6.0 in the project. In https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter it is written that it is deprecated now. In https://github.com/square/retrofit/blob/master

How to suspend a coroutine at a specific point

痴心易碎 提交于 2019-12-10 10:16:47
问题 I am at loss with the following problem. I have the following code: val parentJob: Job = Job() launch(parent = parentJob) { while (true) { if (!parentJob.isCompleted) { // I want to control suspension here println("Resumed") } } } I would like to be able to control, somehow akin to a semaphore, when should the coroutine suspend and when to resume exactly in the commented part of the snippet I know there's suspendCancellableCoroutine but I am unsure how to use it or if it is appropriate here

Exception thrown by deferred.await() within a runBlocking treated as unhandled even after caught

冷暖自知 提交于 2019-12-10 03:34:13
问题 This code: fun main() { runBlocking { try { val deferred = async { throw Exception() } deferred.await() } catch (e: Exception) { println("Caught $e") } } println("Completed") } results in this output: Caught java.lang.Exception Exception in thread "main" java.lang.Exception at org.mtopol.TestKt$main$1$deferred$1.invokeSuspend(test.kt:11) ... This behavior doesn't make sense to me. The exception was caught and handled, and still it escapes to the top-level as an unhandled exception. Is this

Using Deferred<…> in Room DAO with Kotlin Coroutines

你。 提交于 2019-12-07 12:57:55
问题 I'm trying to use Coroutines with a Room database in an Android project. I've found almost no documentation online, and I'm wondering if it is possible to return Deferred<> types in those methods. Something like this: @Dao interface MyObjectDAO { @Query("SELECT * FROM myObject WHERE id_myObject = :idMyObject") suspend fun readMyObjectAsync(idMyObject: Int): Deferred<MyObject> } I've tried this and I get Not sure how to convert a Cursor to this method's return type at compile time. My