Livedata观察员多次致电



我使用的是mvvm和存储库模式。我有一个带有协程的api调用,当点击按钮时返回到livedata并观察livedata片段。一次工作正常,但第二次点击查看模型观察方法称为多次

我的ViewModel类

@HiltViewModel
class OrderViewModel @Inject constructor (
private val repository: OrderRepository
):  ViewModel() {
fun addCourier(body: JsonObject)  = repository.addCourierActivity(body)
}

我的存储库类

class OrderRepository @Inject constructor(
private val gpsApi: GpsApi)
{
private var job: Job? = null
val mutabLiveData = MutableLiveData<DefaultResponse>()
/*private val exceptionHandler = CoroutineExceptionHandler {coroutineContext, throwable ->
mutabLiveData.postValue(DefaultResponse(-1, throwable.message!!))
}*/

fun addCourierActivity(body: JsonObject) : LiveData<DefaultResponse> {

job = CoroutineScope(Dispatchers.IO).launch {
val response = gpsApi.addCourierActivity(body)
Log.e("erer" ,"Coroutine scop called")
if(response.isSuccessful) {
mutabLiveData.postValue(response.body())
} else {
mutabLiveData.postValue(DefaultResponse(1, "Error"))
}

}
return mutabLiveData
}
}

我的碎片类

viewmodel.addCourier(body).observe(viewLifecycleOwner) {
Log.e("dfdfdf","Observing livedata")
Toast.makeText(requireContext(), it.message, Toast.LENGTH_LONG).show()
}

检查这个问题,它几乎与您的问题相同。尝试将Event与事件观察器一起使用。基本上,它会向观测者发送一个一次性事件,该事件可以在您的场景中使用

最新更新