Can I refactor this code ```suspend fun RemoteCli...
# getting-started
r
Can I refactor this code
Copy code
suspend fun RemoteClient.loadBrands(): List<Brand> {
    return suspendCoroutine { cont ->
        load_brands { errCode, result ->
            if (errCode == 0) {
                cont.resume(result)
            } else {
                cont.resumeWithException(errorCodeToException(errCode))
            }
        }
    }
}

suspend fun RemoteClient.searchOfficial(page: Page): List<Remote> {
    return suspendCoroutine { cont ->
        searchOfficial(page) { errCode, remoteList ->
            if (errCode == 0) {
                cont.resume(remoteList)
            } else {
                cont.resumeWithException(errorCodeToException(errCode))
            }
        }
    }
}
So I can basically pass
loadBrands()
/
searchOfficial(page)
, and get the fully-fledged function out?
s
Something like this?
Copy code
suspend fun RemoteClient.searchOfficial(page: Page): List<Remote> {
    return suspendCoroutine { cont ->
        searchOfficial(page, cont.asErrCodeCallback())
    }
}

typealias ErrCodeCallback<T> = (errCode: Int, result: T) -> Unit

fun <T> Continuation<T>.asErrCodeCallback(): ErrCodeCallback<T> = { errCode, result ->
    if (errCode == 0) {
        resume(result)
    } else {
        resumeWithException(errorCodeToException(errCode))
    }
}
😍 1
👍 1