I want to use single live event class to show toast (like flag) Here is my code what I tried. I want to not use peding like flag. how do I fix it?
MainViewModel
class MainViewModel(private val movieRepository: MovieRepository) : ViewModel() {
val keyword = MutableLiveData<String>()
val movieList = MutableLiveData<List<Movie>>()
val msg = MutableLiveData<String>()
val pending: AtomicBoolean = AtomicBoolean(false)
fun findMovie() {
val keywordValue = keyword.value ?: return
pending.set(true)
if (keywordValue.isNullOrBlank()) {
msg.value = "emptyKeyword"
return
}
movieRepository.getMovieData(keyword = keywordValue, 30,
onSuccess = {
if (it.items!!.isEmpty()) {
msg.value = "emptyResult"
} else {
msg.value = "success"
movieList.value = it.items
}
},
onFailure = {
msg.value = "fail"
}
)
}
}
MainActivity
private fun viewModelCallback() {
mainViewModel.msg.observe(this, {
if (mainViewModel.pending.compareAndSet(true, false)) {
when (it) {
"success" -> toast(R.string.network_success)
"emptyKeyword" -> toast(R.string.keyword_empty)
"fail" -> toast(R.string.network_error)
"emptyResult" -> toast(R.string.keyword_result_empty)
}
}
})
}
Solution
Step 1. Copy the
SingleLiveEvent.kt
to your appStep 2. Use from your code.
MainViewModel
MainActivity