Home » Android » android – dagger2 using retrofit2 with Result class-Exceptionshub

android – dagger2 using retrofit2 with Result class-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I’m studying mvvm with AAC examples “https://github.com/android/architecture-samples“.
there is a customized class “Result” that is return Success or Error.
this project use this class in Room repository. So I’m trying to adapt this to retrofit2.
And I wrote some codes wrapped by Result class. But the result return like this.
I can see the right results at okhttp, but the Result class return null.
If I except the Result class, the result is right. but when I use Result class, the result is null. how can I fix it?
ps : one more question, I wanna know the mean of [email protected] there is any way to find out this?

D/OkHttp: {
      "statusCode": 200,
      "body": {
        "dry_score": 79,
        "full_size_image": "url",
        "oily_score": 6,
        "sensitive_score": 76,
        "description": "abcabc",
        "id": 5,
        "price": "54840",
        "title": "abc"
      }
    }
    <-- END HTTP (982-byte body)
D/TAG: Success(null)
sealed class Result<out R> {

    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
    object Loading : Result<Nothing>()

    override fun toString(): String {
        return when (this) {
            is Success<*> -> "Success[data=$data]"
            is Error -> "Error[exception=$exception]"
            Loading -> "Loading"
        }
    }
}

val Result<*>.succeeded
    get() = this is Success && data != null

interface TaskNetwork {

    @GET("products/{id}")
    fun searchItem(
            @Path("id") id:Int
    ): Call<Result<DetailEntity>>
}
class DefaultTasksRepository @Inject constructor(
    @TasksRemoteDataSource private val tasksRemoteDataSource: TasksDataSource,
    @TasksLocalDataSource private val tasksLocalDataSource: TasksDataSource,
    @TaskNetworkSource private val taskNetworkSource: DetailModel,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {

    override suspend fun getRetrofit(id : Int): Result<DetailEntity> {
        withContext(ioDispatcher){
            val request = taskNetworkSource.searchItem(id)
            val response = request.await()

            response.run{
                if(isSuccess){
                    onSuccess {
                        Log.d("TAG",""+response.toString())

                        [email protected] Success(this)
                    }
                    onFailure {
                        [email protected] Error(Exception(it.message))
                    }
                }
            }

        }

        return Error(Exception("Nulll state"))
    }

}
How to&Answers: