Last active
October 14, 2019 16:28
-
-
Save rezaiyan/eecc55c35474c6e6d8b0763871650b89 to your computer and use it in GitHub Desktop.
Binding Observer with LiveData
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 BObserver<T> extends DisposableObserver<T> { | |
private StateLiveData<T> liveData; | |
public BObserver(StateLiveData<T> liveData) { | |
this.liveData = liveData; | |
} | |
@Override | |
protected void onStart() { | |
super.onStart(); | |
liveData.postLoading(); | |
} | |
@Override | |
public void onNext(T t) { | |
liveData.postSuccess(t); | |
} | |
@Override | |
public void onError(Throwable e) { | |
Error error = new Error(-1); | |
if (e instanceof HttpException) { | |
HttpException exception = (HttpException) e; | |
error.setCode(exception.code()); | |
} else if ( | |
e instanceof UnknownHostException || | |
e instanceof SSLHandshakeException || | |
e instanceof SocketTimeoutException) { | |
error.setCode(0); | |
error.setMessage("No internet connection"); | |
} | |
liveData.postError(error); | |
} | |
@Override | |
public void onComplete() { | |
liveData.postComplete(); | |
} |
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 StateLiveData<T> extends MutableLiveData<StateData<T>> { | |
private StateData<T> stateData = new StateData<>(); | |
public void postLoading() { | |
setValue(stateData.loading()); | |
} | |
public void postError(Error error) { | |
setValue(stateData.error(error)); | |
} | |
public void postSuccess(T data) { | |
setValue(stateData.success(data)); | |
} | |
public void postComplete() { | |
setValue(stateData.complete()); | |
} | |
} |
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
vm.livedata.observe(this,response -> { | |
switch (response.getStatus()) { | |
case SUCCESS: | |
case ERROR: | |
case LOADING: | |
case COMPLETE: | |
} | |
}); |
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
StateLiveData<User> livedata = new StateLiveData<>(); | |
Disposable disposable = repository.getUser() | |
.subscribeWith(BObserver<>(liveData)); | |
compositeDisposable.add(disposable); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment