首页 > 解决方案 > 启动协程的单一方法

问题描述

我有一个与 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 线程上?

标签: kotlinkotlin-coroutines

解决方案


嗯..也许我误解了你,但似乎你可以像这样将一段代码作为 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()
        }
    }
}

推荐阅读