我有以下改造客戶端的實作:
private val retrofitClient: Retrofit.Builder by lazy {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.HEADERS
val okHttpClient = OkHttpClient.Builder().addNetworkInterceptor(interceptor)
.cookieJar(SessionCookieJar())
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
Retrofit.Builder()
.baseUrl(URLWebConstants.BASE_URL)
.client(okHttpClient.build())
.addConverterFactory(GsonConverterFactory.create())
}
val postYotiApiService: PostYotiAPIService by lazy {
retrofitClient.build().create(PostYotiAPIService::class.java)
}
interface PostYotiAPIService {
@POST("*url*")
fun postYoti(): Call<PostYotiResponse>
}
然后我有一個帶有呼叫內容的 MainActivityRepository 類:
class MainActivityRepository() {
val client = RetrofitClient
var postYotiLiveData = MutableLiveData<YotiData?>()
fun postYoti(): MutableLiveData<YotiData?> {
val myCall = client.postYotiApiService.postYoti()
myCall.enqueue(object : Callback<PostYotiResponse> {
override fun onFailure(call: Call<PostYotiResponse>, t: Throwable) {
Log.d("Retrofit", "Something went wrong", t)
}
override fun onResponse(
call: Call<PostYotiResponse>,
response: Response<PostYotiResponse>
) {
if (response.isSuccessful) {
postYotiLiveData.postValue(response.body()!!.data)
} else {
postYotiLiveData.postValue(null)
}
}
})
return postYotiLiveData
}
然后在我的 Fragment 的 ViewModel 中,我這樣呼叫函式:
val repository = MainActivityRepository()
fun postYoti(): MutableLiveData<YotiData?> {
return repository.postYoti()
}
最后在我的 Fragment 中,我這樣呼叫:
btnYoti.setOnClickListener {
viewModel.postYoti().observe(viewLifecycleOwner, {
println("Hello World")
}
})
}
我第一次撥打電話時,一切正常,我沒有任何問題,Hello world 列印一次。我第二次打電話 Hello world 被列印了兩次,總共列印了 3 次。第三次 Hello World 被列印 3 次,當我設定斷點時,我可以看到 println 被命中 3 次。每次點擊只需呼叫一次。
uj5u.com熱心網友回復:
您正在觀察 onClickListener 中的 livedata!這意味著每次單擊該按鈕時,一個新的觀察者(帶有 viewLifecycleOwner)將附加到 liveData 并在片段的視圖運行時保持活動狀態。所以每次點擊都會添加另一個永遠不會被移除的觀察者,除非視圖被破壞。當沒有操作時使用觀察(例如,您正在觀察 onViewCreated 中的實時資料,它總是會收到任何更改的通知),操作(如點擊)只需獲取 LiveData 的值并對其進行處理。像這樣
override fun onViewCreated(){
//...
btnYoti.setOnClickListener {
viewModel.postYoti()
}
//Add a getter to your VM to prevent direct access to rep
viewModel.repository.postYotiLiveData.observe(viewLifecycleOwner, {
println("Hello World")
}
}
}
另一方面,您可以使用LiveEvent來防止因恢復片段而導致的冗余列印
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/411648.html
標籤:
