Skip to content

Instantly share code, notes, and snippets.

Avatar
👨‍💻
Learning new things

Akshay Bhange akshaybhange

👨‍💻
Learning new things
View GitHub Profile
View Viewmodel.kt
var productData = MediatorLiveData<Resource<Product>>()
init {
fetchData()
}
fun fetchData() {
productData.addSource(productRepository.getproduct(id)) {
productData.value = it
}
@akshaybhange
akshaybhange / Repository.kt
Created Jul 23, 2019
how to use Resource.kt class to wrap data
View Repository.kt
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 Feb 11, 2020
A generic class that contains data and status about loading this data.
View Resource.kt
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 {
View myFragment.java
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 Jul 26, 2019
how to move your logic from view to viewmodel
View ViewToViewModel.kt
//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 }
}
You can’t perform that action at this time.