Kotlin协程+Flow+Retrofit实现网络请求

Kotlin协程+Flow+Retrofit实现网络请求

导包

  	implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    //test
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //coroutines 协程
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.1"
      //retrofit 2.8.0以上支持协程
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    implementation "com.squareup.retrofit2:converter-gson:2.9.0"
    implementation "com.squareup.okhttp3:logging-interceptor:4.9.0"
    //util
    implementation "com.blankj:utilcode:1.12.5"

代码实现

  • NewsApi:网络接口
interface NewsApi {

    @GET("toutiao/index?key=5376aaa29d5cc66f87e664bb2b4a078b")
    suspend fun getNewsBean(@Query("type") type:String): NewsBean
}
  • NetworkService:接口工具类
object NetworkService {

    private val retrofit = Retrofit.Builder()
        .client(
            OkHttpClient.Builder()
                .callTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                }).build()
        )
        .baseUrl("http://v.juhe.cn/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val newsApi = retrofit.create<NewsApi>()

}
  • LatestNewsUiState:数据返回类
sealed class LatestNewsUiState {
	//成功
    data class Success(var news: NewsBean?) : LatestNewsUiState()
    //失败
    data class Error(var exception: Throwable?) : LatestNewsUiState()
}
  • NewsViewModel:
class NewsViewModel: ViewModel() {
  	private val _uiState = MutableStateFlow<LatestNewsUiState>(LatestNewsUiState.Success(null))

	//使用Flow来监听,替换LiveData
    val uiState: StateFlow<LatestNewsUiState> = _uiState

    fun getNewData() {
        viewModelScope.launch {
            latestNews
                .flowOn(Dispatchers.Default)
                .catch { exception ->
                    _uiState.value = LatestNewsUiState.Error(exception)
                }
                .collect { favoriteNews ->
                    _uiState.value = LatestNewsUiState.Success(favoriteNews)
                }
        }
    }

    private val latestNews: Flow<NewsBean> = flow {
        if (!NetworkUtils.isConnected()) throw RuntimeException("网络未连接")
        //网络请求
        val latestNews = NetworkService.newsApi.getNewsBean("top")
        //返回结果
        emit(latestNews)
    }


}
  • MainActivity
class MainActivity : AppCompatActivity() {
   private val viewModel by viewModels<NewsViewModel>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //监听
  lifecycleScope.launch {
            viewModel.uiState.collect { uiState ->
                when (uiState) {
                    is LatestNewsUiState.Success -> result_tv.text = "result is ${uiState.news}"
                    is LatestNewsUiState.Error -> ToastUtils.showShort("error :${uiState.exception?.message}")
                }
            }
        }
    }

// 点击按钮调用
 viewModel.getNewData()
	
}
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,我来回答你的问题。 首先,Kotlin 是一种基于 JVM 的静态类型编程语言,它的语法简洁易懂,支持函数式编程和面向对象编程。 协程Kotlin 中的一种轻量级线程,可以实现异步编程和并发执行。Retrofit 是一款网络请求库,它可以帮助我们轻松地实现网络请求和数据解析。MVVM 是一种软件架构模式,可以将应用程序分为三个部分:模型、视图和视图模型。 下面是一个基于 Kotlin + 协程 + Retrofit + MVVM 的网络请求的优雅实现: 1. 定义 API 接口 首先定义 API 接口,使用 Retrofit 注解来描述请求方法和参数。 ```kotlin interface ApiService { @GET("api/news") suspend fun getNews(@Query("category") category: String): NewsResponse } ``` 2. 创建数据模型 根据 API 接口的返回数据,我们可以创建一个数据模型。 ```kotlin data class News(val title: String, val content: String) data class NewsResponse(val code: Int, val message: String, val newsList: List<News>) ``` 3. 创建 ViewModel ViewModel 是连接数据模型和视图的中间层,它处理数据逻辑并提供可观察的数据。 ```kotlin class NewsViewModel : ViewModel() { private val _newsList = MutableLiveData<List<News>>() val newsList: LiveData<List<News>> = _newsList fun loadNews(category: String) { viewModelScope.launch { val response = retrofit.create(ApiService::class.java).getNews(category) if (response.code == 200) { _newsList.value = response.newsList } } } } ``` 4. 创建视图 视图负责展示数据,并与用户交互。 ```kotlin class NewsActivity : AppCompatActivity() { private val viewModel by viewModels<NewsViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_news) viewModel.newsList.observe(this, Observer { newsList -> // 更新视图 }) viewModel.loadNews("tech") } } ``` 通过使用 Kotlin + 协程 + Retrofit + MVVM,我们可以实现优雅地网络请求,代码简洁易懂,逻辑清晰。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值