Tag: kotlinx.coroutines

Kotlin协同吞咽exception

我很困惑如何exception处理协同作品。 我希望有可能有一个挂起的function,可以通过例如自己之间的例外同步代码。 所以如果说Retrofit抛出一个IOExceptionexception,我可以在挂起函数链的开始处理这个exception,例如在演示者中向用户显示错误。 我做了这个简单的例子来尝试协同程序,但如果我取消注释throw Exception调用exception后运行的代码失败,但exception不会崩溃的应用程序。 package com.example.myapplication import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Button import android.widget.TextView import kotlinx.coroutines.experimental.delay import kotlinx.coroutines.experimental.launch class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val text = findViewById(R.id.thing_text) val button = findViewById(R.id.thing_button) var count = 0 button.setOnClickListener { launch { count++ // throw Exception(“Boom”) val string = delayedStringOfInt(count) […]

Kotlin协同程序:测试Android Presenter时切换上下文

我最近在Android项目中开始使用kotlin协程,但是我有一些问题。 许多人会称之为代码味道。 我正在使用MVP架构,其中的协程在我的演示者中是这样开始的: // WorklistPresenter.kt … override fun loadWorklist() { … launchAsync { mViewModel.getWorklist() } … launchAsync函数以这种方式实现(在我的WorklistPresenter类扩展的BasePresenter类中): @Synchronized protected fun launchAsync(block: suspend CoroutineScope.() -> Unit): Job { return launch(UI) { block() } } 这个问题是,我正在使用依赖于Android框架的UI协程上下文。 我无法将其更改为另一个协程上下文,而无需运行ViewRootImpl$CalledFromWrongThreadException 。 为了能够unit testing,我创建了一个具有不同的launchAsync实现的launchAsync : protected fun launchAsync(block: suspend CoroutineScope.() -> Unit): Job { runBlocking { block() } return mock() } […]

Kotlin协同工具使用生产和mockito来嘲笑生产工作

我在我的Android应用程序中测试Kotlin协同程序,我正在尝试执行以下unit testing @Test fun `When getVenues success calls explore venues net controller and forwards result to listener`() = runBlocking { val near = “Barcelona” val result = buildMockVenues() val producerJob = produce<List>(coroutineContext) { result.value } whenever(venuesRepository.getVenues(eq(near))) doReturn producerJob // produce corooutine called inside interactor.getVenues(..) interactor.getVenues(near, success, error) // call to real method verify(venuesRepository).getVenues(eq(near)) verify(success).invoke(argThat { […]

未解决的参考:启动

试图运行Kotlin协同程序的一些例子,但不能建立我的项目。 我正在使用最新的Gradle版本 – 4.1 任何建议什么检查/修复? 这里是build.gradle buildscript { ext.kotlin_version = ‘1.1.4-3’ repositories { mavenCentral() } dependencies { classpath “org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version” } } apply plugin: ‘kotlin’ apply plugin: ‘application’ kotlin { repositories { jcenter() } experimental { coroutines ‘enable’ } dependencies { compile “org.jetbrains.kotlinx:kotlinx-coroutines-core:0.18” } } 和main.kt fun main(args: Array) { launch (CommonPool) { delay(1000L) println(“World!”) } […]

Kotlin / Android – 带有lambda的数据类中的KotlinReflectionInternalError

kotlin.reflect.jvm.internal.KotlinReflectionInternalError:反思本地函数,lambdas,匿名函数和局部variables在Kotlinreflection中还没有完全支持 这个exception来自数据类的toString() 。 数据类包含一个lambda。 我不能在我的环境中重现它。 我是否需要重写toString()来排除lambda? 或者lambda在数据类中是不允许的? data class PersistJob( private val id: Int, private val delay: Long = 10_000L, private val maxDelay: Long = 60_000L, private val iteration: Int = 0, private val block: suspend (Int) -> Boolean) { fun getDelay() = minOf(delay, maxDelay) fun withDelayIncreased() = copy( delay = minOf(delay * 2, maxDelay), […]

unit testing使用kotlin协同程序的翻新调用

我正在使用kotlin协程和kotlin改进协程在我正在进行的项目中执行网络请求。 但我无法弄清楚如何让我的unit testing通过逻辑。 这是我的代码: class WorklistInteractor @Inject constructor(private val worklistRepository: WorklistRepository, private val preferenceManager: PreferenceManager) : NetworkInteractor, WorklistDialogContract.Interactor { private var job = Job() override fun getWorklist(listener: OnWorklistResultListener) { job = launch(UI) { val result = async { worklistRepository.getWorklist( ip = preferenceManager.worklistIp, port = preferenceManager.worklistPort).awaitResult() }.await() when (result) { //Successful HTTP result is Result.Ok -> […]

kotlin coroutine抛出java.lang.IllegalStateException:已经恢复,但得到了值的位置

一般来说,我对Kotlin协同程序和Android开发很陌生。 在玩弄了解它是如何工作的时候,我遇到了一个我似乎无法解决的错误。 从基本的活动,我尝试连接到googleApiClient。 权限是可以的。 我希望使用kotlin协同程序以直接方式从LocationManager获取位置更新,以便稍后使用此位置对象。 我第一次在模拟器中改变自己的位置时,它工作的很好,第二次改变我的位置,它崩溃,像这样的exception: FATAL EXCEPTION: main Process: com.link_value.eventlv, PID: 32404 java.lang.IllegalStateException: Already resumed, but got value Location[gps 48.783000,2.516180 acc=20 et=+59m16s372ms alt=0.0 {Bundle[mParcelledData.dataSize=40]}] at kotlinx.coroutines.experimental.AbstractContinuation.resumeImpl(AbstractContinuation.kt:79) at kotlinx.coroutines.experimental.AbstractContinuation.resume(AbstractContinuation.kt:72) at com.link_value.eventlv.View.Create.NewEventLvActivity$await$2$1.onLocationChanged(NewEventLvActivity.kt:100) at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:297) at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java) at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:242) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) override fun onCreate(savedInstanceState: Bundle?) { […]

不能执行kotlin协程(没有这样的方法exception

我从kotlin例子中拿出了这个简单的代码片段: fun main(args: Array) = runBlocking { withTimeout(1300L) { repeat(1000) { i -> println(“I’m sleeping $i …”) delay(500L) } } } 当我尝试运行它时,它会抛出 java.lang.NoSuchMethodError: kotlinx.coroutines.experimental.ScheduledKt.withTimeout$default(JLjava/util/concurrent/TimeUnit;Lkotlin/jvm/functions/Function2;ILjava/lang/Object;)Ljava/lang/Object; 我用kotlinVersion =’1.1.51′ 有什么建议?

如何限制kotlin协同程序的最大并发性

我有一个序列(从File.walkTopDown),我需要在他们每个人上运行一个长时间运行的操作。 我想使用Kotlin的最佳实践/协同程序,但是我要么没有并行性,要么太多的并行性,并打“太多打开的文件”IO错误。 File(“/Users/me/Pictures/”).walkTopDown() .onFail { file, ex -> println(“ERROR: $file caused $ex”) } .filter { … only big images… } .map { file -> async { // I *think* I want async and not “launch”… ImageProcessor.fromFile(file) } } 这似乎并不是并行运行,而我的多核CPU从来没有超过1 CPU的价值。 有没有一种方法与协程运行“NumberOfCores并行操作”价值的延期工作? 我使用Kotlin Coroutines来查看multithreading ,首先创建所有作业然后加入它们,但这意味着完成序列/文件树遍历繁重的处理加入步骤之前,似乎… iffy! 将其拆分成一个收集和一个流程步骤意味着收集可以在处理之前运行。 val jobs = … the Sequence above… .toSet() println(“Found […]

操作数堆栈上的错误types与Kotlin协同程序

这段代码与Kotlin 1.2.10编译成功,但是当我运行它时,它会java.lang.VerifyError: Bad type on operand stack产生一个java.lang.VerifyError: Bad type on operand stack 。 如果我删除了Test类并将其提取出来,它将按预期工作。 这是为什么? import kotlinx.coroutines.experimental.delay import kotlinx.coroutines.experimental.launch import kotlinx.coroutines.experimental.runBlocking import java.util.* import kotlin.concurrent.schedule class Test { fun scheduleTimeout() { Timer(true).schedule(300) { launch { runSuspended(“hello”) } } } suspend fun runSuspended(txt: String) = println(txt) } fun main(args: Array) { Test().scheduleTimeout() runBlocking { delay(10000) } […]