RxHttp - 轻量级、可扩展、易使用、完美兼容MVVM、MVC架构的网络封装类库 (2)

定义MVCHttpCallback,用于将网络请求结果回调给UI界面

abstract class MVCHttpCallback<T> { private val type: Type init { val arg = TypeUtil.getType(javaClass) type = TypeBuilder .newInstance(TKResponse::class.java) .addTypeParam(arg) .build() } fun getType(): Type { return this.type } /** * 请求开始时回调,可以在此加载loading对话框等,默认为空实现 */ open fun onStart() {} /** * 抽象方法,请求成功回调,返回内容为泛型,对应TKResponse的data */ abstract fun onSuccess(result: T?) /** * 抽象方法,请求失败回调,返回内容为code(错误码),msg(错误信息) */ abstract fun onFailure(code: Int, msg: String?) /** * 上传进度回调,默认为空实现 */ open fun onProgress(readBytes: Long, totalBytes: Long) {} /** * 请求完成时回调,请求成功之后才会回调此方法,默认为空实现 */ open fun onComplete() {} }

定义网络接口,封装GET/POST等网络请求

object MVCApi { /** * GET请求 * context:上下文 * url:请求url * params:参数列表,可为null * tag:标识一个网络请求 * callback:网络请求回调 */ inline fun <reified T> httpGet( context: Context, url: String, params: Map<String, Any?>?, tag: Any? = null, callback: MVCHttpCallback<T> ) { RxHttp.getInstance().get(context) .url(url) .params(params) .tag(tag) .enqueue(simpleHttpCallback(callback)) } /** * POST请求 * context:上下文 * url:请求url * params:参数列表,可为null * tag:标识一个网络请求 * callback:网络请求回调 */ inline fun <reified T> httpPost( context: Context, url: String, params: Map<String, Any?>?, tag: Any? = null, callback: MVCHttpCallback<T> ) { RxHttp.getInstance().post(context) .url(url) .params(params) .tag(tag) .enqueue(simpleHttpCallback(callback)) } ...... inline fun <reified T> simpleHttpCallback(callback: MVCHttpCallback<T>): HttpCallback<TKResponse<T>> { return object : HttpCallback<TKResponse<T>>(callback.getType()) { override fun onStart() { super.onStart() callback.onStart() } override fun onNext(response: TKResponse<T>?) { if (response != null) { if (response.isSuccess()) { callback.onSuccess(response.data) } else { return onError(ServerException(response.code, response.msg)) } } else { return onError(NullResponseException(TKErrorCode.ERRCODE_RESPONSE_NULL, TKErrorCode.ERRCODE_RESPONSE_NULL_DESC)) } } override fun onError(e: Throwable?) { handleThrowable(e).run { callback.onFailure(first, second) } } override fun onComplete() { super.onComplete() callback.onComplete() } override fun onProgress(readBytes: Long, totalBytes: Long) { super.onProgress(readBytes, totalBytes) callback.onProgress(readBytes, totalBytes) } } }

在View层如Activity中调用网络接口

MVCApi.httpGet( context = baseActivity, url = TKURL.URL_GET, params = null, tag = null, callback = object : MVCHttpCallback<List<Banner>>() { override fun onStart() { LogUtils.d(TAG, "onButtonGet onStart() called") } override fun onSuccess(result: List<Banner>?) { Log.d(TAG, "onButtonGet onSuccess() called with: result = $result") } override fun onFailure(code: Int, msg: String?) { Log.d(TAG, "onButtonGet onFailure() called with: code = $code, msg = $msg") } override fun onComplete() { Log.d(TAG, "onButtonGet onComplete() called") } })

具体使用可以参考demo代码,demo中有详细的示例演示MVC项目如何使用RxHttp

MVVM项目

定义Activity基类BaseMvvmActivity

abstract class BaseMvvmActivity<VM : BaseViewModel, VDB : ViewDataBinding> : AppCompatActivity(){ lateinit var viewModel: VM lateinit var binding: VDB protected abstract fun getLayoutId(): Int final override fun onCreate(savedInstanceState: Bundle?) { onCreateStart(savedInstanceState) super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, getLayoutId()) binding.lifecycleOwner = this createViewModel() onCreateEnd(savedInstanceState) } protected open fun onCreateStart(savedInstanceState: Bundle?) {} protected open fun onCreateEnd(savedInstanceState: Bundle?) {} /** * 创建ViewModel */ private fun createViewModel() { val type = findType(javaClass.genericSuperclass) val modelClass = if (type is ParameterizedType) { type.actualTypeArguments[0] as Class<VM> } else { BaseViewModel::class.java as Class<VM> } viewModel = ViewModelProvider(this).get(modelClass) } private fun findType(type: Type): Type?{ return when(type){ is ParameterizedType -> type is Class<*> ->{ findType(type.genericSuperclass) } else ->{ null } } } }

定义ViewModel的基类BaseViewModel

open class BaseViewModel(application: Application) : AndroidViewModel(application) { /** * 网络仓库 */ protected val networkbaseRepository: NetworkRepository = NetworkRepository.instance /** * 上下文 */ protected var context: Context = application.applicationContext }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpsywy.html