Skip to content

Instantly share code, notes, and snippets.

View akshaybhange's full-sized avatar
👨‍💻
Learning new things

Akshay Bhange akshaybhange

👨‍💻
Learning new things
View GitHub Profile
var productData = MediatorLiveData<Resource<Product>>()
init {
fetchData()
}
fun fetchData() {
productData.addSource(productRepository.getproduct(id)) {
productData.value = it
}
@akshaybhange
akshaybhange / Repository.kt
Created July 23, 2019 12:47
how to use Resource.kt class to wrap data
fun getProduct(id:Int): LiveData<Resource<Product>> {
val productData = MutableLiveData<Resource<Product>>()
productData.value = Resource.Loading()
productWebService
.getProduct(id)
.enqueue(object : Callback<Product> {
override fun onResponse(
call: Call<Product>,
response: Response<JsonObject>
) {
@akshaybhange
akshaybhange / Resource.kt
Last active February 11, 2020 16:00
A generic class that contains data and status about loading this data.
sealed class Resource<T>(
val data: T? = null,
val message: String? = null
) {
class Success<T>(data: T) : Resource<T>(data)
class Loading<T>(data: T? = null) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
}
enum class Status {
private void subscribeToModel() {
// Observe product data
viewModel.getObservableProduct().observe(getViewLifecycleOwner(), new Observer<Product>() {
@Override
public void onChanged(@Nullable Product product) {
mTitle.setText(product.title);
}
});
}
@akshaybhange
akshaybhange / ViewToViewModel.kt
Last active July 26, 2019 06:17
how to move your logic from view to viewmodel
//this is wrong
//writing logic for filtering items in your Fragmet 
var filterList = simpleList.filter { it%2 == 0 }
//this is correct
//function created for it in your ViewModel
fun getEvenNumbers(simpleList : List<Int>):List<Int> {
return simpleList.filter { it%2 == 0 }
}