Help guys! I want to pass a network call to this f...
# android
a
Help guys! I want to pass a network call to this function but I couldn't:
Copy code
suspend fun <T> wrapNetworkCall(call: () -> T) : NetworkResult<T> {
    return try {
        NetworkResult.Success(call())
    } catch (e: HttpException) {
        if (e.code() == 400)
            NetworkResult.BadRequestError(e)
        else NetworkResult.Error(e)
    }
}
Copy code
coroutineScope.launch {
    val result = wrapNetworkCall {
        Api.retrofitService.getCurrent() // Suspension functions can be called only within coroutine body
    }
}
c
you need to make the function parameter suspended:
wrapNetworkCall(call: suspend () -> T) : NetworkResult<T> {
j
Or
Copy code
inline suspend fun <T> wrapNetworkCall(call: () -> T) : NetworkResult<T> {
    return try {
        NetworkResult.Success(call())
    } catch (e: HttpException) {
        if (e.code() == 400)
            NetworkResult.BadRequestError(e)
        else NetworkResult.Error(e)
    }
}
c
yeah inlining the function will also work
r
Slightly related, CallAdapter is a better/ cleaner fit for this pattern. Here’s a nice library that implements exactly this: https://github.com/haroldadmin/NetworkResponseAdapter
a
Thank you everyone!