当前位置:网站首页>Kotlin协程+Flow+Retrofit实现网络请求
Kotlin协程+Flow+Retrofit实现网络请求
2022-04-22 06:19:00 【许三多2020】
导包
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()
}
版权声明
本文为[许三多2020]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Gary__123456/article/details/120509590
边栏推荐
- L2-001 emergency rescue (extension of shortest Dijkstra - number of shortest paths & maximum weight of paths)
- 2019.1.2版的Idea使用教程
- Idea does not display the run dashboard view window
- D. Determine the Photo Position (简单找子串)(2021牛客暑期多校训练营1)
- 2021学习计划
- A.Binary Seating (概率) (2021年度训练联盟热身训练赛第五场)
- Codeforces Round #774 (Div. 2)
- Codeforces Round #778
- 1. Jam packed (Game 5 of 2021 training League warm-up training competition)
- 762 · 最长公共子序列 II
猜你喜欢

L2-001 emergency rescue (extension of shortest Dijkstra - number of shortest paths & maximum weight of paths)

C.Ducky Debugging(简单判断/签到)(2021年度训练联盟热身训练赛第五场 )

HDU Ice_ Cream's world I

L2-004 is this a binary search tree? (first order input & judgment search Binary Tree & second order output)

换根dp(啊啊啊啊啊)

Leetcode - 6 - (chaîne multiplicatrice, prochain élément plus grand < Ⅰ Ⅱ Ⅲ >, K liste de chaînes inversées)

内部类使用说明(静态、实例、局部)

1005 Monopoly 同余求解(2021中国大学生程序设计竞赛CCPC-网络选拔赛重赛)

A. Binary seating (the fifth game of 2021 training League warm-up training competition)

系统日志文件过大优化
随机推荐
323 · 字符串游戏
Leetcode - 3 - (string addition, maximum number of consecutive 1 < Ⅰ Ⅲ >, maximum difficulty of the exam, deletion of the penultimate node of the linked list)
Leetcode - 4 - (longest substring without repeated characters, candy distribution, binary tree traversal)
并发编程的艺术(2):Synchronized的使用场景
重写与重载的定义与区别
Codeforces Round #634 (Div. 3)
D. Determine the Photo Position (简单找子串)(2021牛客暑期多校训练营1)
838 · 子数组和为K
并发编程的艺术(3):深入理解Synchronized的原理
递归反转链表
要是我再犯这种憨憨错误就.../(ㄒoㄒ)/~~
Codeforces Round #776 (Div. 3)
快排与归并排序
LeetCode - 7 - (二叉树的最近公共祖先、轮转数组、二叉树的直接、下一个排列、组合总和)
Solution to the 45 problem of Niuke XB monthly competition
This关键字详细概述
A.Binary Seating (概率) (2021年度训练联盟热身训练赛第五场)
SQL Server quick start
[Opt 31-67] Problem axi_ Interconnect RTL error
15 · 全排列