Android 使用改装+;协同程序

Android 使用改装+;协同程序,android,kotlin,retrofit,Android,Kotlin,Retrofit,我正在学习为不同的任务使用改装库,但还不完全了解它是如何工作的。 主要任务是获取车身,如果响应代码为200,则overwise(所有其他代码)只需设置标志: import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.Respon

我正在学习为不同的任务使用改装库,但还不完全了解它是如何工作的。 主要任务是获取车身,如果响应代码为200,则overwise(所有其他代码)只需设置标志:

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.http.GET

interface APIService {

    @GET("/")
    suspend fun getRoot(): Response<ResponseBody>
}

...

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
      
       ...

       
      button.setOnClickListener {

           val url = editText.text.toString()  
           //  url = "https://"+ "google.coN"
           val retrofit = Retrofit.Builder()
                .baseUrl(url)
                .build() 
           val service = retrofit.create(APIService::class.java)
           ...

           CoroutineScope(Dispatchers.IO).launch {
                val response  = service.getRoot()
                withContext(Dispatchers.Main) {
                    if (response.isSuccessful){
                        Ok = true // address is ok
                    } else {
                        Ok = false // this address dosnt exist
                                    }
                  ....      
                        }
                    }
              }
        }
}
导入kotlinx.coroutines.CoroutineScope
导入kotlinx.coroutines.Dispatchers
导入kotlinx.coroutines.launch
导入kotlinx.coroutines.withContext
导入okhttp3.responsebook
2.回应
进口改装2.改装
导入文件2.http.GET
接口服务{
@获取(“/”)
suspend fun getRoot():响应
}
...
类MainActivity:AppCompatActivity(){
重写创建时的乐趣(savedInstanceState:Bundle?){
...
button.setOnClickListener{
val url=editText.text.toString()
//url=“https://”+“google.coN”
val reformation=reformation.Builder()
.baseUrl(url)
.build()
val service=reformation.create(APIService::class.java)
...
协同路由示波器(Dispatchers.IO)。启动{
val response=service.getRoot()
withContext(Dispatchers.Main){
if(response.issucessful){
Ok=true//地址正常
}否则{
Ok=false//此地址不存在
}
....      
}
}
}
}
}
代码运行良好(从一些导师示例中重新录制),链接良好,但只要地址错误或格式不正确,应用程序就会崩溃,它需要格式良好的URL(“https://”+)

如何修改代码和添加异常,并对URL进行预格式化

PS:Prob直接使用OkHTTP更好,但我使用集成 为清晰起见,删除了带有此改装代码的GSON lib


Thanx.

有几件事可以帮你做到这一点,它会更有效:

  • 创建视图模型并在活动中创建该模型的实例

    button.setOnClickListener {
      ....
    
       viewModel.performRequest { response ->
    
            // ok = response
        }
    }
    
  • 在视图模型中,创建用于执行后台任务的方法,如下所示:

    private fun loadNetworkRequest(block:suspend()->Unit):作业{

    返回viewModelScope.launch{

    试试{

    block()

    }捕获(例如:异常){

    Toast.makeText(appContext,ex.message,Toast.LENGTH\u SHORT).show()

    }

    }

    }

  • 为服务文件中的请求添加
    suspend
    关键字,您希望使用此方法执行该请求

    @GET(“category/”)

    suspend fun getCategories():响应

  • 在视图模型中执行请求,如下所示:

    fun performRequest(回调:(布尔)->Unit){

    loadNetworkRequest{

    val response=service.getRoot()

    callback.invoke(response.issusccessful)

    }

    }

  • 在活动中调用请求方法

    button.setOnClickListener {
      ....
    
       viewModel.performRequest { response ->
    
            // ok = response
        }
    }
    

  • 首先,创建一个
    sealed
    类来保存结果

    sealed class ApiResult<out T : Any?>
    
    data class Success<out T : Any?>(val data: T) : ApiResult<T>()
    
    data class ApiError(val exception: Exception) : ApiResult<Nothing>()
    
    CoroutineScope(Dispatchers.IO).launch {
          val result: ApiResult<ResponseBody>  = handleApi( { service.getRoot() } )
          when(result){
              is ApiResult.Success -> // result.data will give you ResponseBody
              is ApiResult.ApiError -> // result.exception will provide the error
          }
    }
    
    最后,使用下面的代码访问结果

    sealed class ApiResult<out T : Any?>
    
    data class Success<out T : Any?>(val data: T) : ApiResult<T>()
    
    data class ApiError(val exception: Exception) : ApiResult<Nothing>()
    
    CoroutineScope(Dispatchers.IO).launch {
          val result: ApiResult<ResponseBody>  = handleApi( { service.getRoot() } )
          when(result){
              is ApiResult.Success -> // result.data will give you ResponseBody
              is ApiResult.ApiError -> // result.exception will provide the error
          }
    }
    
    CoroutineScope(Dispatchers.IO)。启动{
    val result:apireult=handleApi({service.getRoot()})
    何时(结果){
    是ApiResult.Success->//result.data将为您提供ResponseBy
    is APIRSULT.APIRROR->//result.exception将提供错误信息
    }
    }
    
    try-catch块应该会有帮助。您能提供错误代码吗?