kotlin-coroutines

Return value only of the faster coroutine

拜拜、爱过 提交于 2019-12-30 05:00:07
问题 How can I run multiple coroutines in parallel and return only the value of the one that finishes first? Real-life scenario, I have two data sources - Database and API service . I don't care where does the data originate from, I just need it fast. How can I query both Database and API service and cancel the other request when the one finishes? In RxJava world this would be equal to Amb operator. How can I achieve similar behaviour using coroutines? 回答1: I came up with following implementation:

kotlin coroutine withTimeout does not cancel when using withContext to get non-blocking code

僤鯓⒐⒋嵵緔 提交于 2019-12-24 12:59:10
问题 I am using withContext to transform a function into a suspending function which does not block the calling thread. For this I used https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761 as reference. Now I would like to invoke this function with a timeout. For this I use withTimeout to call the function as such: @Test internal fun timeout() { runBlocking { logger.info("launching") try { withTimeout(1000) { execute() } } catch (e: TimeoutCancellationException) {

Kotlin parallel computation of large array

冷暖自知 提交于 2019-12-24 11:27:36
问题 I have a large array and need compute result based on each item of this array. My PC's processor has 2 cores. I have compared different ways to achieve parallel execution in Kotlin. I wrote simple example to illustrate this. First way is Java parallel stream, second is plain Kotlin map, third is coroutine version of map. fun p() = runBlocking { val num = (0 until 1_000_000).toList() println(measureTimeMillis { num.stream().parallel().map { it * 2 }.collect(Collectors.toList()) }) println

Coroutine doens't start?

血红的双手。 提交于 2019-12-24 06:21:46
问题 Based on this post throttleFirst function: fun <T> throttleFirst( skipMs: Long = 700L, scope: CoroutineScope = viewModelScope, action: (T) -> Unit ): (T) -> Unit { var throttleJob: Job? = null return { param: T -> if (throttleJob?.isCompleted != false) { throttleJob = coroutineScope.launch { destinationFunction(param) delay(skipMs) } } } } I'm using it like this: View <Button android:onClick="@{viewModel.myClickListener}" .../> ViewModel: fun myClickListener() = View.OnClickListener { _ ->

How to use Fuel with coroutines in Kotlin?

风格不统一 提交于 2019-12-24 00:32:55
问题 I want to get an API request and save request's data to a DB. Also want to return the data (that is written to DB). I know, this is possible in RxJava, but now I write in Kotlin coroutines, currently use Fuel instead of Retrofit (but a difference is not so large). I read How to use Fuel with a Kotlin coroutine, but don't understand it. How to write a coroutine and methods? UPDATE Say, we have a Java and Retrofit, RxJava. Then we can write a code. RegionResponse: @AutoValue public abstract

Wait until Kotlin coroutine finishes in onCreateView()

假如想象 提交于 2019-12-23 13:05:10
问题 I have an initialization block in onCreateView , where some variables are assigned from SharedPreferences, DB or Network (currently from SharedPreferences). I want to update views with these values in onViewCreated . But they update with empty values before a coroutine in onCreateView finishes. How to wait until the coroutine finishes in main thread? override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { ... GlobalScope.launch

produce<Type> vs Channel<Type>()

删除回忆录丶 提交于 2019-12-23 05:04:21
问题 Trying to understand channels. I want to channelify the android BluetoothLeScanner. Why does this work: fun startScan(filters: List<ScanFilter>, settings: ScanSettings = defaultSettings): ReceiveChannel<ScanResult?> { val channel = Channel<ScanResult>() scanCallback = object : ScanCallback() { override fun onScanResult(callbackType: Int, result: ScanResult) { channel.offer(result) } } scanner.startScan(filters, settings, scanCallback) return channel } But not this: fun startScan(scope:

Does Xamarin support Kotlin coroutines in a Xamarin Android Binding Library?

廉价感情. 提交于 2019-12-23 04:03:47
问题 I have an Android Binding Library with Kotlin code, and it exits whenever it hits runBlocking{} in the Kotlin code. E(28583:28691) ERROR [19] - The worker thread caught an exception: Failed resolution of: Lkotlinx/coroutines/BuildersKt; E(28583:28691) Java.Lang.NoClassDefFoundError: Failed resolution of: Lkotlinx/coroutines/BuildersKt; ---> Java.Lang.ClassNotFoundException: Didn't find class "kotlinx.coroutines.BuildersKt" on path: DexPathList[[zip file "/data/app/de.mycompany.app.myproduct-1

Does Xamarin support Kotlin coroutines in a Xamarin Android Binding Library?

折月煮酒 提交于 2019-12-23 04:03:34
问题 I have an Android Binding Library with Kotlin code, and it exits whenever it hits runBlocking{} in the Kotlin code. E(28583:28691) ERROR [19] - The worker thread caught an exception: Failed resolution of: Lkotlinx/coroutines/BuildersKt; E(28583:28691) Java.Lang.NoClassDefFoundError: Failed resolution of: Lkotlinx/coroutines/BuildersKt; ---> Java.Lang.ClassNotFoundException: Didn't find class "kotlinx.coroutines.BuildersKt" on path: DexPathList[[zip file "/data/app/de.mycompany.app.myproduct-1

Testing Android Room with LiveData, Coroutines and Transactions

血红的双手。 提交于 2019-12-22 10:49:07
问题 I want to test my database layer and I have caught myself in a catch-22 type of a situation. The test case consists of two things: Save some entities Load the entities and assert the database mapping works as expected The problem, in short, is that: Insert is a suspend method, which means it needs to be run in runBlocking{} Query returns a LiveData of the result, which is also asynchronous. Therefore it needs to be observed. There's this SO question that explains how to do that. In order to