https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

mohsenoid

03/27/2019, 9:47 AM
Hi there, We are migrating some parts of our over-used RxJava codes to Coroutines, but we cannot decide which one is the best practice as a new learners! old code is something like this:
Copy code
interface CallLogDataStore {
    fun getCallLogs(): Single<Array<CallLogEntity>>
}

class CallLogDataStoreImpl @Inject internal constructor(
    private val contentResolver: ContentResolver
) : CallLogDataStore {

    override fun getCallLogs(): Single<Array<CallLogEntity>> = Single.fromCallable(::queryAllCallLogs)
we can change it to
Deferred
from the source:
Copy code
interface CallLogDataStore {
    suspend fun getCallLogsAsync(): Deferred<Array<CallLogEntity>>
}

class CallLogDataStoreImpl @Inject internal constructor(
    private val contentResolver: ContentResolver
) : CallLogDataStore {

    override suspend fun getCallLogsAsync(): Deferred<Array<CallLogEntity>> =
        suspendCoroutine { queryAllCallLogs() }
or just keep it simple and let the use-case decide to execute it using Coroutines or not,
Copy code
interface CallLogDataStore {
    fun getCallLogs(): Array<CallLogEntity>
}

class CallLogDataStoreImpl @Inject internal constructor(
    private val contentResolver: ContentResolver
) : CallLogDataStore {

    override fun getCallLogs(): Array<CallLogEntity> =
        queryAllCallLogs()

interface CallLogRepository {
    suspend fun getCallLogsAsync(): Deferred<Array<CallLog>>
}

class CallLogRepositoryImpl @Inject internal constructor(
    private val dataStore: CallLogDataStore,
    private val mapper: CallLogMapper
) : CallLogRepository {

    override suspend fun getCallLogsAsync(): Deferred<Array<CallLog>> =
        GlobalScope.async { dataStore.getCallLogs().map(mapper::mapFromEntity).toTypedArray() }
}
any suggestion?
a

amrelmasry

03/27/2019, 10:01 AM
I think no need to return
Deferred
from this
suspend
function, you can return the array directly:
Copy code
interface CallLogDataStore {
    suspend fun getCallLogs(): Array<CallLogEntity>
}
and the imp. can be like this:
Copy code
class CallLogRepositoryImpl(...) : CallLogRepository {
override suspend fun getCallLogsAsync(): Array<CallLogEntity> =
        suspendCoroutine { queryAllCallLogs() 
}
I think this is better than if you let the use-case the one who decides. because the store itself can now enforce something like executing all the queries on single thread for example.
👍 1
2 Views