Last active
August 19, 2018 15:41
-
-
Save ibrahimsn98/b9e1ba95c408cbc5623fba2471053ba4 to your computer and use it in GitHub Desktop.
android-mvvm-with-dagger-2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ListViewModel extends ViewModel { | |
private final RepoRepository repoRepository; | |
private CompositeDisposable disposable; | |
private final MutableLiveData<List<Repo>> repos = new MutableLiveData<>(); | |
private final MutableLiveData<Boolean> repoLoadError = new MutableLiveData<>(); | |
private final MutableLiveData<Boolean> loading = new MutableLiveData<>(); | |
@Inject | |
public ListViewModel(RepoRepository repoRepository) { | |
this.repoRepository = repoRepository; | |
disposable = new CompositeDisposable(); | |
fetchRepos(); | |
} | |
LiveData<List<Repo>> getRepos() { | |
return repos; | |
} | |
LiveData<Boolean> getError() { | |
return repoLoadError; | |
} | |
LiveData<Boolean> getLoading() { | |
return loading; | |
} | |
private void fetchRepos() { | |
loading.setValue(true); | |
disposable.add(repoRepository.getRepositories().subscribeOn(Schedulers.io()) | |
.observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSingleObserver<List<Repo>>() { | |
@Override | |
public void onSuccess(List<Repo> value) { | |
repoLoadError.setValue(false); | |
repos.setValue(value); | |
loading.setValue(false); | |
} | |
@Override | |
public void onError(Throwable e) { | |
repoLoadError.setValue(true); | |
loading.setValue(false); | |
} | |
})); | |
} | |
@Override | |
protected void onCleared() { | |
super.onCleared(); | |
if (disposable != null) { | |
disposable.clear(); | |
disposable = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment