1.在activity调用方式
class MainActivity : BaseActivity<ActivityMainBinding>() {
private val viewModel: UserViewModel by viewModels()
private val adapter: UserAdapter by lazy { UserAdapter() }
override fun initView(savedInstanceState: Bundle?) {
initNetworkObserver()
initViewObserver()
//网络请求(这里是下拉刷新)
mBindingView.smartRefresh.setOnRefreshListener {
lifecycleScope.launch {
viewModel.searchUser()
}
}
}
//网络请求监听
private fun initNetworkObserver() {
lifecycleScope.launch {
viewModel.userResult.collect {
adapter.setList(listOf(it))
mBindingView.smartRefresh.finishRefresh()
}
}
}
//视图事件监听
private fun initViewObserver() {
viewModel.viewEvent.observeEvent(getParentActivity()) {
when (it) {
ViewEvent.DismissDialog -> {
}
else -> {
}
}
}
}
2. ViewMode写法
class UserViewModel(application: Application) : AndroidViewModel(application) {
//视图
private val _viewEvent: SharedFlowEvents<ViewEvent> = SharedFlowEvents()
val viewEvent = _viewEvent.asSharedFlow()
//数据
private val _userResult: MutableSharedFlow<Data> = MutableSharedFlow()
val userResult = _userResult.asSharedFlow()
suspend fun searchUser() {
viewModelScope.launch {
flow<User> {
//调用请求方法
val data = Api.api.getUser()
if (data.data != null) {
_userResult.emit(data.data!!)
} else {
_viewEvent.setEvent(ViewEvent.ShowToast("查询失败"))
}
_viewEvent.setEvent(ViewEvent.DismissDialog)
}.onStart {
// delay(2000)
_viewEvent.setEvent(ViewEvent.ShowDialog)
}.catch { ex ->
//当网络请求尚未完成,且抛出了error,则返回Error出去
val networkResult = call(ex)
LogUtil.d(networkResult.toString())
_viewEvent.setEvent(ViewEvent.DismissDialog, ViewEvent.ShowToast("登录失败:${networkResult.second}"))
}.collect()
}
}
}
3.请求封装Api类
package com.ceshi.network
import android.annotation.SuppressLint
import com.ceshi.BuildConfig
import com.ceshi.config.ApiConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.security.*
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.*
/**
* "ht" 创建
* 界面名称以及功能:网络请求Retrofit2+Coroutine(协程)
*/
object Api {
private const val DEFAULT_TIMEOUT: Long = 30
val api: ApiService by lazy {
//支持RxJava2
val retrofit = Retrofit.Builder().baseUrl(ApiConfig.BaseUrl)
.addConverterFactory(ScalarsConverterFactory.create()) //添加ScalarsConverterFactory支持
.addConverterFactory(GsonConverterFactory.create())//可以接收自定义的Gson,当然也可以不传
.client(unsafeOkHttpClient)
.build()
return@lazy retrofit.create(ApiService::class.java)
}
// Install the all-trusting trust manager TLS
private val unsafeOkHttpClient: OkHttpClient
get() = try {
// Install the all-trusting trust manager TLS
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
val okBuilder = OkHttpClient.Builder()
okBuilder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
okBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
okBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
okBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
okBuilder.addInterceptor(if (BuildConfig.DEBUG) HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) else HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE))
/*okBuilder.addInterceptor { chain ->
val request: Request = chain.request().newBuilder()
.header("Cache-Control", "public") //如果只有一个请求头,就使用这
.addHeader("header2","aa") //如果是多个请求头,就是用addHeader
.removeHeader("Pragma")//删除掉请求过程中的所有key为Pragma的请求头
.build()
chain.proceed(request);
}*/
okBuilder.hostnameVerifier { _, _ -> true }
okBuilder.build()
} catch (e: Exception) {
throw RuntimeException(e)
}
@SuppressLint("CustomX509TrustManager")
private val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
@SuppressLint("TrustAllX509TrustManager")
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
}
@SuppressLint("TrustAllX509TrustManager")
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return arrayOf()
}
})
}
4.http接口ApiService类
interface ApiService {
//ApiConfig为请求链接入(http://datavmap-public.oss-cn-hangzhou.aliyuncs.com/areas/csv/100000_province.json)
@GET(ApiConfig.city) //get无参
suspend fun getCity(): City
@GET(SearchMusic)//get带参
suspend fun getSearchMusic(
@Query("keyword") keyword: String
): SearchList
@POST(ApiConfig.user)//post无参
suspend fun getUser(): User
@POST(ApiConfig.Uid)//post带参
suspend fun getUid(
@Body uid: Uid
): UidData
}