Skip to content

Commit

Permalink
代码优化:单次网络请求用协程实现,此时可以去掉Retrofit的addCallAdapterFactory
Browse files Browse the repository at this point in the history
  • Loading branch information
lelelongwang committed Jun 18, 2021
1 parent b368d8e commit a071737
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 56 deletions.
25 changes: 13 additions & 12 deletions app/src/main/java/com/longjunhao/wanjetpack/api/WanJetpackApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ interface WanJetpackApi {
* 获取项目分类列表
*/
@GET("/project/tree/json")
fun getProjectCategory(): LiveData<ApiResponse<List<ProjectCategory>>>
suspend fun getProjectCategory(): ApiResponse<List<ProjectCategory>>

/**
* 获取项目列表数据
Expand All @@ -64,7 +64,7 @@ interface WanJetpackApi {
* 获取公众号列表
*/
@GET("/wxarticle/chapters/json")
fun getWechatName(): LiveData<ApiResponse<List<WechatCategory>>>
suspend fun getWechatName(): ApiResponse<List<WechatCategory>>

/**
* 获取某个公众号历史数据
Expand All @@ -79,27 +79,27 @@ interface WanJetpackApi {
* 登录
*/
@POST("/user/login")
fun login(
suspend fun login(
@Query("username") username: String,
@Query("password") password: String
): LiveData<ApiResponse<User>>
): ApiResponse<User>

/**
* 注册成功和登录成功的json一样,通过判断errorCode即可。
*/
@POST("/user/register")
fun register(
suspend fun register(
@Query("username") username: String,
@Query("password") password: String,
@Query("repassword") repassword: String
): LiveData<ApiResponse<User>>
): ApiResponse<User>

/**
* 退出,todo 清理cookie
* 退出成功为是判断errorCode即可:{"data":null,"errorCode":0,"errorMsg":""}
*/
@GET("/user/logout/json")
fun logout(): LiveData<ApiResponse<User>>
suspend fun logout(): ApiResponse<User>

/**
* 获取收藏列表,请求后的json和 获取首页文章列表几乎一样。但是我的收藏获取的ApiArticle中没有"collect"字符串。
Expand All @@ -118,9 +118,9 @@ interface WanJetpackApi {
* todo 还有一种常见没有实现:收藏站外文章
*/
@POST("lg/collect/{id}/json")
fun collect(
suspend fun collect(
@Path("id") id: Int
): LiveData<ApiResponse<ApiArticle>>
): ApiResponse<ApiArticle>

/**
* 文章列表 取消收藏:
Expand All @@ -131,9 +131,9 @@ interface WanJetpackApi {
* todo 网站、网址的收藏、编辑、删除没有实现
*/
@POST("lg/uncollect_originId/{id}/json")
fun unCollect(
suspend fun unCollect(
@Path("id") id: Int
): LiveData<ApiResponse<ApiArticle>>
): ApiResponse<ApiArticle>


companion object {
Expand All @@ -149,11 +149,12 @@ interface WanJetpackApi {
.build()

//注意:如果只是用Paging、Flow不需要LiveDataCallAdapterFactory或CoroutineCallAdapterFactory。
//其实用了协程后,是不需要添加addCallAdapterFactory的
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(LiveDataCallAdapterFactory())
//.addCallAdapterFactory(LiveDataCallAdapterFactory())
.build()
.create(WanJetpackApi::class.java)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class WanJetpackRepository @Inject constructor(
).flow
}

fun getProjectCategory(): LiveData<ApiResponse<List<ProjectCategory>>> {
suspend fun getProjectCategory(): ApiResponse<List<ProjectCategory>> {
return api.getProjectCategory()
}

Expand All @@ -61,7 +61,7 @@ class WanJetpackRepository @Inject constructor(
).flow
}

fun getWechatName(): LiveData<ApiResponse<List<WechatCategory>>> {
suspend fun getWechatName(): ApiResponse<List<WechatCategory>> {
return api.getWechatName()
}

Expand All @@ -72,16 +72,16 @@ class WanJetpackRepository @Inject constructor(
).flow
}

fun login(username: String, password: String): LiveData<ApiResponse<User>> {
suspend fun login(username: String, password: String): ApiResponse<User> {
Log.d("WanJetpackRepository", "login: ljh name=$username pass=$password")
return api.login(username, password)
}

fun register(username: String, password: String, repassword: String): LiveData<ApiResponse<User>> {
suspend fun register(username: String, password: String, repassword: String): ApiResponse<User> {
return api.register(username, password, repassword)
}

fun logout(): LiveData<ApiResponse<User>>{
suspend fun logout(): ApiResponse<User>{
return api.logout()
}

Expand All @@ -92,11 +92,11 @@ class WanJetpackRepository @Inject constructor(
).flow
}

fun collect(id: Int): LiveData<ApiResponse<ApiArticle>> {
suspend fun collect(id: Int): ApiResponse<ApiArticle> {
return api.collect(id)
}

fun unCollect(id: Int): LiveData<ApiResponse<ApiArticle>> {
suspend fun unCollect(id: Int): ApiResponse<ApiArticle> {
return api.unCollect(id)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ class ProjectFragment : Fragment() {

private fun subscribeUi(categoryAdapter: ProjectCategoryAdapter,adapter: ProjectAdapter){
viewModel.projectCategory.observe(viewLifecycleOwner, Observer {
categoryAdapter.submitList(it)
viewModel.currentSelectedItem.postValue(it[0])
if (it.errorCode == 0) {
categoryAdapter.submitList(it.data)
viewModel.currentSelectedItem.postValue(it.data?.get(0))
}
})
viewModel.currentSelectedItem.observe(viewLifecycleOwner, Observer {
Log.d("TAG", "subscribeUi: ljh it${it.id}+ name${it.name}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,9 @@ class LoginFragment : Fragment() {
//viewModel.login.observe(viewLifecycleOwner, Observer {
//todo 此处传参数是个不好的方案,应该不需要传参数。
viewModel.login(username, password).observe(viewLifecycleOwner, Observer {
Log.d("LoginFragment", "subscribeUi: ljh it=$it")
if (it != null) {
viewModel.name.postValue(it.username)
viewModel.user.postValue(it)
if (it.errorCode == 0) {
viewModel.name.postValue(it.data?.username)
viewModel.user.postValue(it.data)
viewModel.isLogin.postValue(true)
findNavController().navigateUp()
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,9 @@ class RegisterFragment : Fragment() {
//viewModel.register.observe(viewLifecycleOwner, Observer {
//todo 此处传参数是个不好的方案,应该不需要传参数。
viewModel.register(username, password, repassword).observe(viewLifecycleOwner, Observer {
if (it != null) {
viewModel.name.postValue(it.username)
viewModel.user.postValue(it)
if (it.errorCode == 0) {
viewModel.name.postValue(it.data?.username)
viewModel.user.postValue(it.data)
viewModel.isLogin.postValue(true)
//返回到上一个fragment,注意与popBackStack()的区别
//findNavController().navigateUp()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ class WechatFragment : Fragment() {

private fun subscribeUi() {
viewModel.wechatName.observe(viewLifecycleOwner, Observer {
initViewPager(it)
if (it.errorCode == 0) {
it.data?.let { list -> initViewPager(list) }
}
})
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.longjunhao.wanjetpack.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
Expand Down Expand Up @@ -32,10 +33,14 @@ class HomeArticleViewModel @Inject constructor(
/**
* todo :和adapter一样,重复的部分应该可以写在baseViewModel中
*/
fun collect(id: Int) = repository.collect(id)
fun collect(id: Int) = liveData {
emit(repository.collect(id))
}

/**
* todo :和adapter一样,重复的部分应该可以写在baseViewModel中
*/
fun unCollect(id: Int) = repository.unCollect(id)
fun unCollect(id: Int) = liveData {
emit(repository.unCollect(id))
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.longjunhao.wanjetpack.viewmodels

import androidx.lifecycle.*
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.longjunhao.wanjetpack.data.ApiArticle
Expand Down Expand Up @@ -28,8 +31,8 @@ class ProjectViewModel @Inject constructor(
MutableLiveData<ProjectCategory>()
}

val projectCategory = repository.getProjectCategory().map {
it.data ?: ArrayList()
val projectCategory = liveData {
emit(repository.getProjectCategory())
}

fun getProjectArticle(categoryId: Int): Flow<PagingData<ApiArticle>> {
Expand All @@ -40,7 +43,11 @@ class ProjectViewModel @Inject constructor(
return newResult
}

fun collect(id: Int) = repository.collect(id)
fun collect(id: Int) = liveData {
emit(repository.collect(id))
}

fun unCollect(id: Int) = repository.unCollect(id)
fun unCollect(id: Int) = liveData {
emit(repository.unCollect(id))
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.longjunhao.wanjetpack.viewmodels

//import com.longjunhao.wanjetpack.util.SharedPreferencesObject
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.map
import com.longjunhao.wanjetpack.data.WanJetpackRepository
import com.longjunhao.wanjetpack.data.user.User
Expand Down Expand Up @@ -67,18 +67,19 @@ class SharedViewModel @Inject constructor(
/**
* todo 为什么不行获取不到username、password的值呢?
*/
val login = repository.login(username.value ?: "", password.value ?: "").map {
/*val login = repository.login(username.value ?: "", password.value ?: "").map {
if (it.errorCode == 0) it.data else null
}
}*/

fun login(username: String, password: String) = repository.login(username, password).map {
if (it.errorCode == 0) it.data else null
fun login(username: String, password: String) = liveData {
emit(repository.login(username, password))
}

fun register(username: String, password: String, repassword: String) =
repository.register(username, password, repassword).map {
if (it.errorCode == 0) it.data else null
}
fun register(username: String, password: String, repassword: String) = liveData {
emit(repository.register(username, password, repassword))
}

val logout = repository.logout()
val logout = liveData {
emit(repository.logout())
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.longjunhao.wanjetpack.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
Expand Down Expand Up @@ -31,7 +32,11 @@ class WechatArticleViewModel @Inject constructor(
return newResult
}

fun collect(id: Int) = repository.collect(id)
fun collect(id: Int) = liveData {
emit(repository.collect(id))
}

fun unCollect(id: Int) = repository.unCollect(id)
fun unCollect(id: Int) = liveData {
emit(repository.unCollect(id))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,7 @@ class WechatViewModel @Inject constructor(
private val repository: WanJetpackRepository
) : ViewModel() {

/**
* TODO: 1. 没有用LiveData,不知道需不需要, 2. 为什么没有用Transformations.map()和Transformations.switchMap(),3. LiveData用Flow替换了
*
*/
val wechatName = repository.getWechatName().map {
it.data ?: ArrayList()
val wechatName = liveData {
emit( repository.getWechatName())
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.longjunhao.wanjetpack.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import androidx.paging.cachedIn
Expand Down Expand Up @@ -29,7 +30,11 @@ class WendaViewModel @Inject constructor(
return newResult
}

fun collect(id: Int) = repository.collect(id)
fun collect(id: Int) = liveData {
emit(repository.collect(id))
}

fun unCollect(id: Int) = repository.unCollect(id)
fun unCollect(id: Int) = liveData {
emit(repository.unCollect(id))
}
}

0 comments on commit a071737

Please sign in to comment.