• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Autodesk/coroutineworker: Kotlin Coroutine-based workers for native

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

Autodesk/coroutineworker

开源软件地址(OpenSource Url):

https://github.com/Autodesk/coroutineworker

开源编程语言(OpenSource Language):

Kotlin 100.0%

开源软件介绍(OpenSource Introduction):

CoroutineWorker

Build Status

Maven Central

Specs

  • Supported on Native, JVM, and JS (legacy and IR) (feel free to contribute adding more targets)
  • Kotlin 1.6.20

Gradle

To use in your multiplatform project, update your common dependencies in your gradle configuration:

kotlin {
    sourceSets {
        commonMain {
            dependencies {
                implementation "com.autodesk:coroutineworker:0.8.2"
            }
        }
    }
}

CoroutineWorker uses gradle module metadata. We recommend adding the following to your settings.gradle to take advantage of that (not necessary for Gradle 6+):

enableFeaturePreview('GRADLE_METADATA')

About

CoroutineWorker helps support multi-threaded coroutine usage in common code that works in Kotlin/Native and on JVM until kotlinx.coroutines has full support for native, multi-threaded coroutines.

Projects Using this on your Devices

Sample Usage

Spawning Asynchronous Work

Use execute to start background work from common code:

val worker = CoroutineWorker.execute {
  // - In here, `this` is a `CoroutineScope`
  // - Run suspend functions, call launch, etc.
  // - This code runs in a thread pool
}

// Tells the worker to cancel (uses standard coroutine cancellation)
worker.cancel()

// Tells the worker to cancel; it suspends until cancellation is finished
worker.cancelAndJoin()

Waiting on Asynchronous Work to Complete

From a coroutine context (i.e. somewhere you can call a suspend fun), use withContext to kick off work to another thread. It will non-blocking/suspend wait for the cross-thread work to complete:

suspend fun doWork() {
  val result = CoroutineWorker.withContext {
    // This is similar to execute, but it returns
    // the result of the work at the end of this lambda
    1
  }
  print(result) // prints 1
}

This is like using withContext on JVM to switch coroutine contexts. You can also properly pass a dispatcher, which will be used on JVM: withContext(Dispatchers.IO) { … }. The idea here is that this will be easy to migrate when we do get multi-threaded coroutine support in Kotlin/Native.

Waiting on Asynchronous Callback-based Work

Use threadSafeSuspendCallback to bridge callback-style async work into your code as a suspend fun:

suspend fun performNetworkFetch() {
  val result = threadSafeSuspendCallback { completion ->
    // example: fetch network data that isn't coroutine-compatible
    fetchNetworkData { networkResult ->
      // notify that async work is complete
      completion(networkResult)
    }
  }

  // result is now available here
}

Sample Project

In the sample directory, there is a sample project that demonstrates adding CoroutineWorker to an iOS + JVM library. We just used the sample library from IntelliJ's template for a "Mobile Shared Library." In the sample is a function called performWork (common code) that takes a completion lambda and demonstrates CoroutineWorker.execute. In tests, we use K/N concurrency helpers from kotlinx.atomicfu to demonstrate capturing a result across threads in K/N and executing this function.

CoroutineWorker Prefers Frozen State

Object detachment (i.e. transferring object ownership from one thread to another) is relatively difficult to achieve (outside of simple scenarios) compared to working with objects that are frozen and immutable. Because of this, CoroutineWorker prefers taking the frozen, immutable route:

  • Lambdas passed to CoroutineWorker are automatically frozen when they are going to be passed across threads.
  • The result value from withContext is also frozen.

Tips for Working with Frozen State

  • Be careful about what your frozen lambdas capture; those objects will be frozen too. Especially, watch for implicit references to this.
  • Call ensureNeverFrozen() on objects that you don't expect to ever be frozen.

IO-Bound Work

In the JVM world, you typically write code like this for managing IO-bound work with coroutines:

withContext(Dispatchers.IO) {
    // IO writes
}

Similar behavior is supported in CoroutineWorker for Kotlin/Native via the IODispatcher. To use it in common code, make an expect val Dispatchers.IO: CoroutineDispatcher that returns IODispatcher for Kotlin/Native and Dispatchers.IO for JVM, and pass that to CoroutineWorker.withContext when performing IO-bound worker.




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap