kotlin - 启动协程的单一方法
问题描述
我有一个与 RoomDB 对话并共享首选项的 StorageRepository。我希望这种通信通过 IO 线程上的单一方法进行。我一直这样做到现在 -
class StorageRepository(private val coroutineDispatcher: CoroutineContext = Dispatchers.Main
) : CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + coroutineDispatcher
override fun storeUserDetails(userDetails: UserDetails) {
roomDB.store(userDetails)
}
override fun storeTimeStamp(timeStamp: String) {
sharedPrefs.store(timeStamp)
}
private fun executeAllOpsOnIOThread() = launch {
withContext(Dispatchers.IO) {
//Any DB write, read operations to be done here
}
}
}
我的问题是我怎样才能传递roomDB.store(userDetails)
和传递,sharedPrefs.store(timeStamp)
以便executeAllOpsOnIOThread()
所有数据库通信都发生在 IO 线程上?
解决方案
嗯..也许我误解了你,但似乎你可以像这样将一段代码作为 lambda 函数传递:
class StorageRepository(
private val coroutineDispatcher: CoroutineContext = Dispatchers.Main
) : CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + coroutineDispatcher
override fun storeUserDetails(userDetails: UserDetails) = executeAllOpsOnIOThread {
roomDB.store(userDetails)
}
override fun storeTimeStamp(timeStamp: String) = executeAllOpsOnIOThread {
sharedPrefs.store(timeStamp)
}
private fun executeAllOpsOnIOThread(block: () -> Unit) = launch {
withContext(Dispatchers.IO) {
block()
}
}
//async get
fun getTimestamp(): Deferred<String> = getOnIOThread { sharedPrefs.getTime() }
private fun <T> getOnIOThread(block: () -> T):Deferred<T> = async {
withContext(Dispatchers.IO) {
block()
}
}
}
推荐阅读
- google-cloud-platform - 我们可以安排 StackDriver Logging 来导出日志吗?
- javascript - 如何将两个或多个包含多个对象的数组合并为一个并增加它们的 ID?
- python - csv排序和删除python
- python - python:循环遍历Excel中的索引并用字符串替换
- angular - Angular 7 - 从 Angular 组件生成 URL
- c# - C# 按时间更改表行类
- rest - OAuth2 用于 REST API,紧耦合 SPA 作为唯一客户端
- python - 在 Jupyter 中写入目录权限
- python - 有没有办法使用 Wand(ImageMagick Python 绑定)修剪透明区域?
- bootstrap-4 - 如何更改 bootstrap 4.1 scrollspy(moving) 活动链接颜色?