Alex208
Alex208

Reputation: 23

Single method to launch a coroutine

I have a StorageRepository that talks with RoomDB and also shared prefs. I want this communication to happen through a single method on a IO thread. I have done this until now -

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
        }
    }
}

My question is how can I pass roomDB.store(userDetails) and sharedPrefs.store(timeStamp) to executeAllOpsOnIOThread() so that all DB communication happens on IO thread?

Upvotes: 1

Views: 286

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8422

Hmm.. Maybe I misunderstand you but it seems you can just pass a block of code as lambda function like this:

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()
        }
    }
}

Upvotes: 1

Related Questions