我想從服務器呼叫一些 API,為此我使用了改造!
我為我的專案選擇了MVVM架構,我有2 個片段!
片段 A 和 B 。
片段 A:呼叫 API 并在RecyclerView
.
片段 B :是詳細頁面并顯示資料資訊。
當從設備/模擬器(在片段 B 中)點擊后退按鈕并顯示片段 B 時,再次呼叫 API!
我認為在使用時viewmodel
,APIS 只是第一次呼叫!
我只想第一次呼叫 API!
存盤庫類:
class FragmentARepository @Inject constructor(private val api: ApiServices) {
suspend fun dataList(): Flow<MyResponse<ResponseDataList>> {
return flow {
emit(MyResponse.loading())
emit(MyResponse.success(api.dataList().body()))
}.catch { emit(MyResponse.error(it.message.toString())) }.flowOn(Dispatchers.Main)
}
}
視圖模型類:
@HiltViewModel
class FragmentAViewModel @Inject constructor(private val repository: FragmentARepository) : ViewModel() {
val dalaListLive = MutableLiveData<List<ResponseDataList.Meal>>()
fun loadDataList() = viewModelScope.launch(Dispatchers.IO) {
repository.dataList().collect { dataList.postValue(it.body()?.meals!!) }
}
}
片段A類:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//InitViews
binding?.apply {
viewModel.loadDataList()
viewModel.dataList.observe(viewLifecycleOwner) {
dataAdapter.setData(it.data.meals)
dataRv.setupRecyclerView(
LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false),
dataAdapter
)
}
}
}
為什么我的 API 每次都呼叫?我只想要一次。
我只想要一次。
uj5u.com熱心網友回復:
你的假設是錯誤的。ViewModel 不是“呼叫 API 一次”。每當您請求它們時,它們都會呼叫 API。在您的 FragmentA 中,您從 onViewCreated 請求視圖模型的資料,當您重新輸入此片段時(例如,從 FragmentB單擊回傳時)執行
然而,ViewModel 被創建并且是持久的(在一定程度上): https ://developer.android.com/topic/libraries/architecture/viewmodel
因此,如果您希望 API 呼叫發生一次,您可以在 ViewModel 的 init 中呼叫它:
@HiltViewModel
class FragmentAViewModel @Inject constructor(private val repository: FragmentARepository) : ViewModel() {
val dalaListLive = MutableLiveData<List<ResponseDataList.Meal>>()
init {
viewModelScope.launch(Dispatchers.IO) {
repository.dataList().collect {
dataList.postValue(it.body()?.meals!!)
}
}
}
在您的 FragmentA 中,只需觀察dalaListLive:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//InitViews
binding?.apply {
viewModel.dataList.observe(viewLifecycleOwner) {
dataAdapter.setData(it.data.meals)
dataRv.setupRecyclerView(
LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false),
dataAdapter
)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507363.html