Browse Source
Convert FavoritesViewModel to kotlin and optimise code
renovate/org.robolectric-robolectric-4.x
Convert FavoritesViewModel to kotlin and optimise code
renovate/org.robolectric-robolectric-4.x
Ammar Githam
4 years ago
3 changed files with 47 additions and 48 deletions
-
2app/build.gradle
-
38app/src/main/java/awais/instagrabber/fragments/FavoritesFragment.kt
-
51app/src/main/java/awais/instagrabber/viewmodels/FavoritesViewModel.kt
@ -1,19 +1,48 @@ |
|||
package awais.instagrabber.viewmodels; |
|||
package awais.instagrabber.viewmodels |
|||
|
|||
import androidx.lifecycle.MutableLiveData; |
|||
import androidx.lifecycle.ViewModel; |
|||
import android.app.Application |
|||
import androidx.lifecycle.AndroidViewModel |
|||
import androidx.lifecycle.LiveData |
|||
import androidx.lifecycle.MutableLiveData |
|||
import awais.instagrabber.db.datasources.FavoriteDataSource |
|||
import awais.instagrabber.db.entities.Favorite |
|||
import awais.instagrabber.db.repositories.FavoriteRepository |
|||
import awais.instagrabber.db.repositories.RepositoryCallback |
|||
|
|||
import java.util.List; |
|||
class FavoritesViewModel(application: Application) : AndroidViewModel(application) { |
|||
private val _list = MutableLiveData<List<Favorite>>() |
|||
val list: LiveData<List<Favorite>> = _list |
|||
|
|||
import awais.instagrabber.db.entities.Favorite; |
|||
private val favoriteRepository: FavoriteRepository = FavoriteRepository.getInstance(FavoriteDataSource.getInstance(application)) |
|||
|
|||
public class FavoritesViewModel extends ViewModel { |
|||
private MutableLiveData<List<Favorite>> list; |
|||
init { |
|||
fetch() |
|||
} |
|||
|
|||
fun fetch() { |
|||
favoriteRepository.getAllFavorites(object : RepositoryCallback<List<Favorite>> { |
|||
override fun onSuccess(favorites: List<Favorite>?) { |
|||
_list.postValue(favorites ?: emptyList()) |
|||
} |
|||
|
|||
override fun onDataNotAvailable() {} |
|||
}) |
|||
} |
|||
|
|||
fun delete(favorite: Favorite, onSuccess: () -> Unit) { |
|||
favoriteRepository.deleteFavorite(favorite.query, favorite.type, object : RepositoryCallback<Void> { |
|||
override fun onSuccess(result: Void?) { |
|||
onSuccess() |
|||
favoriteRepository.getAllFavorites(object : RepositoryCallback<List<Favorite>> { |
|||
override fun onSuccess(result: List<Favorite>?) { |
|||
_list.postValue(result ?: emptyList()) |
|||
} |
|||
|
|||
public MutableLiveData<List<Favorite>> getList() { |
|||
if (list == null) { |
|||
list = new MutableLiveData<>(); |
|||
override fun onDataNotAvailable() {} |
|||
}) |
|||
} |
|||
return list; |
|||
|
|||
override fun onDataNotAvailable() {} |
|||
}) |
|||
} |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue