Skip to content

Instantly share code, notes, and snippets.

@raghunandankavi2010
Created February 12, 2021 05:22
Show Gist options
  • Save raghunandankavi2010/0808248dc6e5ff524711e92d1b5fd78b to your computer and use it in GitHub Desktop.
Save raghunandankavi2010/0808248dc6e5ff524711e92d1b5fd78b to your computer and use it in GitHub Desktop.
ViewModel
private val vendorDetailsRepo = VendorDetailsRepo()
private val _vendorType: MutableLiveData<Vendor> = MutableLiveData()
val vendorType: LiveData<Vendor>
get() = _vendorType
var vendor: LiveData<Result<Vendors>> = _vendorType.switchMap { vendor ->
vendor.ifExists {
liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
emit(vendorDetailsRepo.getVendorDetails(it))
}
}
}
fun setVendorType(vendorType: String) {
val update = Vendor(vendorType)
_vendorType.value = update
}
data class Vendor(val vendorType: String) {
fun <T> ifExists(f: (String) -> LiveData<T>): LiveData<T> {
return if (vendorType.isBlank()) {
AbsentLiveData.create()
} else {
f(vendorType)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment