Tag: kotlinx.coroutines

如何通过reflection运行挂起方法?

有一个协程块可以运行暂停function。 但我通过reflectioninvoke函数。 这是java风格的调用,显然一个简单的调用是行不通的。 有没有办法异步运行reflection的方法? 如何等待这个方法? import kotlin.coroutines.experimental.* class TestClass(val InString: String) { suspend fun printString() { println(InString) } } fun launch(context: CoroutineContext, block: suspend () -> Unit) = block.startCoroutine(StandaloneCoroutine(context)) private class StandaloneCoroutine(override val context: CoroutineContext): Continuation { override fun resume(value: Unit) {} override fun resumeWithException(exception: Throwable) { val currentThread = Thread.currentThread() currentThread.uncaughtExceptionHandler.uncaughtException(currentThread, exception) } } […]

使用Anko协程扩展的正确方法是什么?

所以我正在从RxJava移植一个示例应用程序到Kotlin / Anko Corountines,我想知道如果我正在做它最好的(第一)方法: fun getPopulationList() { val ref = asReference() async(UI) { try { ref().setCurrentState(ViewState.State.LOADING) val background = bg { repository.populationResponse().execute().body() } ref().let { it.response = background.await() it.mvpView?.onGetData(it.response) it.setCurrentState(ViewState.State.FINISH) } } catch (e: Exception) { e.printStackTrace() ref().mvpView?.onError(e) } } } 我正在使用MVP架构,其中我的Presenter基类有一个CompositeSubscription和在onDestroy的片段或活动方法简单退订,并清除CompositeSubscription对象。 但是我想知道如果从asReference()函数是相同的,没有必要保存一个Deferred的列表,然后迭代它并逐个取消。 顺便说一句,如果我添加一个Thread.sleep(5000)来模拟一个大事务,并销毁碎片,我可以在logcat中看到的HTTP响应即使片段不可见/销毁,而RxJava没有发生,所以我想我我没有正确使用。

kotlinx-coroutines-reactive如何处理null场景?

kotlinx-coroutines-reactive使org.reactivestreams.Publisher拥有awaitXXX方法: val person = peopleReactiveRepository.findById(personId).awaitSingle() 如果没有人可以通过人员IDfind,则此调用将引发NoSuchElementException,并且此exception不能直接在用户代码中处理 。 而Spring MVC ExceptionHandler不能将这个exception转换成用户友好的响应。 java.util.NoSuchElementException: No value received via onNext for awaitSingle at kotlinx.coroutines.experimental.reactive.AwaitKt$awaitOne$$inlined$suspendCancellableCoroutine$lambda$1.onComplete(Await.kt:131) ~[kotlinx-coroutines-reactive-0.22.1.jar:na] at reactor.core.publisher.StrictSubscriber.onComplete(StrictSubscriber.java:123) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE] at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onComplete(Operators.java:1327) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE] at reactor.core.publisher.FluxHide$SuppressFuseableSubscriber.onComplete(FluxHide.java:137) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE] at reactor.core.publisher.FluxMap$MapSubscriber.onComplete(FluxMap.java:130) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE] at reactor.core.publisher.MonoNext$NextSubscriber.onComplete(MonoNext.java:96) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE] at com.mongodb.reactivestreams.client.internal.ObservableToPublisher$1.onComplete(ObservableToPublisher.java:78) ~[mongodb-driver-reactivestreams-1.6.0.jar:na] 我可以找出的一个方法如下: val person = peopleRepository.findById(personId).awaitFirstOrDefault(null) if (person == null) { // do something } 但我不认为这是一个优雅的方式。 例如,可以提供一个名为awaitSingleOptional的方法。 […]

将回调代码迁移到暂停function

我正在使用协程将我的Android代码从Java重新分解到Kotlin,但是我没有find一种简单的方法来将基于回调的代码重写为挂起的函数。 一个基本的例子是一个警告popup框,返回一个结果,在Javascript中它将是这样的: let value = prompt(“please insert a value”) console.log(“Value:”+value) 我会在Kotlin翻译如下: class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { //Standard activity initialization super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Actual code… launch { val value = resolvable(UI) { success, error -> //Build a simple popup prompt with AlertDialog val input = EditText(this@MainActivity) val builder = AlertDialog.Builder(this@MainActivity) .setTitle(“please insert […]

当使用kotlin协同程序时,如何对一个调用暂停function的函数进行unit testing?

我有这样的课 class SomeClass { fun someFun() { // … Some synchronous code async { suspendfun() } } private suspend fun suspendFun() { dependency.otherFun().await() // … other code } } 我想unit testingsomeFun()所以我写了一个unit testing,看起来像这样: @Test fun testSomeFun() { runBlocking { someClass.someFun() } // … verifies & asserts } 但是,这似乎不工作,因为runBlocking实际上并没有阻止执行,直到runBlocking内的一切完成。 如果我直接在runBlocking里面测试suspendFun()它可以像预期的那样工作,但是我想能够一起测试someFun() 。 任何线索如何测试同步和异步代码的function?

当几个协程运行时,不要退出Kotlin程序

在我的程序的几个地方,我使用launch来启动一个协同工作,做一些后台任务。 然后,在某个时候,我从main函数返回。 我的程序的简化版本可能如下所示: fun main(args : Array) { launch { delay(10000) // some long running operation println(“finished”) } } 现在,协程按预期启动并开始运行 – 然后程序退出。 如果我不从main返回或用thread替换launch ,一切都按预期工作。 所以我怎么能 ,因为我没有跟踪在我的程序中启动的所有协程(因此我不能使用.join()或.await() ), 确保所有的协程在我的程序退出之前完成?

使用mockito的Kotlin协同程序unit testing

当我尝试模拟和validation一个正在调用暂停function的活动时,我得到了下面的内容 错误: 论据是不同的! 通缉:userManager.getAccountInfo((onCreate_callsGetAccountInformation $ 1)kotlinx.coroutines.experimental.CoroutineScope。() – > kotlin.Unit); – > at com.pharmacy.AccountActivityTests $ onCreate_callsGetAccountInformation $ 1.doResume(AccountActivityTests.kt:117)实际的调用有不同的参数:userManager.getAccountInfo(()kotlinx.coroutines.experimental.CoroutineScope。() – > kotlin.Unit) – > at com.pharmacy.AccountActivity $ loadAccountInfoAsync $ 1 $ 1.doResume(AccountActivity.kt:199) 码: 我有我的unit testing用runBlocking装饰如下所示: @Test fun onCreate_callsGetAccountInformation() = runBlocking { whenever(userManager.getAccountInfo()).thenReturn(AccountInformation()) subject = Robolectric.setupActivity(AccountActivity::class.java) verify(userManager).getAccountInfo() } 这里 – > usermanager.getAccountInfo()是一个挂起的函数。

取消孩子如何在Kotlin协同工作?

根据文档cancelChildren应该取消一个协程的孩子,但离开父母不受影响(“这个工作本身的状态不受影响。”)但是,如果我有代码 val outer = launch { try { launch (coroutineContext) { try { // work here } catch (ex: Exception) { println(“In inner catch”) } finally { println(“In inner finally”) } } delay(5000) // so the outer job is running when I cancel it } catch (ex: CancellationException) { println(“In outer catch”) } finally { […]

Kotlin挂起函数递归调用

突然发现,递归调用挂起函数需要更多的时间,然后调用相同的函数,但没有suspend修饰符,所以请考虑下面的代码片段(基本的斐波那契数列计算): suspend fun asyncFibonacci(n: Int): Long = when { n asyncFibonacci(n + 2) – asyncFibonacci(n + 1) n == -1 -> 1 n == 0 -> 0 n == 1 -> 1 n >= 2 -> asyncFibonacci(n – 1) + asyncFibonacci(n – 2) else -> throw IllegalArgumentException() } 如果我调用这个函数并用下面的代码来衡量它的执行时间: fun main(args: Array) { val totalElapsedTime […]

Android中的Kotlin协程:为什么要使用Anko中的bg()而不是async()?

我今天开始在Android上使用Kotlin协同程序,并且注意到Anko对它们有一套自己的辅助方法。 我明白为什么asReference()存在,但我不明白为什么bg() asReference() ,因为核心协程库lib已经具有async() 。 bg()代码非常简单,它内部使用async() : @PublishedApi internal var POOL = newFixedThreadPoolContext(2 * Runtime.getRuntime().availableProcessors(), “bg”) inline fun bg(crossinline block: () -> T): Deferred = async(POOL) { block() } 那么使用bg()而不是async()的优点是什么? 对于Android应用程序, async()效率低下吗?