我最喜欢在 Android 上执行网络请求的方法(使用 Retrofit)。它看起来像这样:
// NetworkApi.kt
interface NetworkApi {
@GET("users")
suspend fun getUsers(): List<User>
}
Run Code Online (Sandbox Code Playgroud)
在我的 ViewModel 中:
// MyViewModel.kt
class MyViewModel(private val networkApi: NetworkApi): ViewModel() {
val usersLiveData = flow {
emit(networkApi.getUsers())
}.asLiveData()
}
Run Code Online (Sandbox Code Playgroud)
最后,在我的活动/片段中:
//MyActivity.kt
class MyActivity: AppCompatActivity() {
private viewModel: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel.usersLiveData.observe(this) {
// Update the UI here
}
}
}
Run Code Online (Sandbox Code Playgroud)
我喜欢这种方式的原因是因为它本身就可以与 Kotlin flow 配合使用,非常易于使用,并且有很多有用的操作(flatMap 等)。
但是,我不确定如何使用此方法优雅地处理网络错误。我能想到的一种方法是用作Response<T>
网络 API 的返回类型,如下所示:
// NetworkApi.kt
interface NetworkApi {
@GET("users")
suspend …
Run Code Online (Sandbox Code Playgroud) 我正在使用 Kotlin flow 和 Android Paging 3 库编写一个玩具 Android 应用程序。该应用程序调用一些远程 API 来获取照片列表,并RecyclerView
使用PagingDataAdapter
.
我发现后面的代码pagingAdapter.submitData()
没有执行。
这是代码片段(该函数位于 a 中Fragment
):
fun refreshList() {
lifecycleScope.launch {
photosViewModel.listPhotos().collect {
// `it` is PagingData<Photo>
pagingAdapter.submitData(it)
Log.e(TAG, "After submitData")
}
}
}
Run Code Online (Sandbox Code Playgroud)
日志After submitData
不打印。
但是,如果我将日志记录放在该行的前面pagingAdapter.submitData()
,则会打印它,如下所示:
fun refreshList() {
lifecycleScope.launch {
photosViewModel.listPhotos().collect {
// `it` is PagingData<Photo>
Log.e(TAG, "Before submitData")
pagingAdapter.submitData(it)
}
}
}
Run Code Online (Sandbox Code Playgroud)
打印日志Before submitData
没有问题。
请问为什么会出现这种情况?
android kotlin android-paging android-paging-library kotlin-coroutines