123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- package com.luticate.utils.business;
-
- import com.luticate.utils.dbo.LuPromiseError;
-
- import java.util.List;
- import java.util.Vector;
-
- /**
- *
- * Created by robin on 11/27/15.
- */
- public class LuPromise<T> {
-
- public enum LuPromiseStatus {
- Running,
- Resolved,
- Failed
- }
-
- private List<LuConsumer<T>> _onSuccess = new Vector<>();
-
- private List<LuConsumer<LuPromiseError>> _onFailed = new Vector<>();
-
- protected LuPromiseStatus _status = LuPromiseStatus.Running;
-
- protected T _data = null;
-
- protected LuPromiseError _error = null;
-
- public LuPromiseStatus getStatus()
- {
- return _status;
- }
-
- public T getData()
- {
- return _data;
- }
-
- public LuPromiseError getError()
- {
- return _error;
- }
-
- public LuPromise<T> then(LuConsumer<T> onSuccess, LuConsumer<LuPromiseError> onFailed)
- {
- _onFailed.add(onFailed);
- if (_status == LuPromiseStatus.Failed) {
- if (onFailed != null) {
- onFailed.execute(_error);
- }
- }
- return then(onSuccess);
- }
-
- public LuPromise<T> then(LuConsumer<T> onSuccess)
- {
- _onSuccess.add(onSuccess);
- if (_status == LuPromiseStatus.Resolved) {
- if (onSuccess != null) {
- onSuccess.execute(_data);
- }
- }
- return this;
- }
-
- public LuPromise<T> resolve(T data)
- {
- if (_status == LuPromiseStatus.Running) {
- _data = data;
- _error = null;
- _status = LuPromiseStatus.Resolved;
- onSuccess();
- }
- return this;
- }
-
- public LuPromise<T> reject(LuPromiseError error)
- {
- if (_status == LuPromiseStatus.Running) {
- _data = null;
- _error = error;
- _status = LuPromiseStatus.Failed;
- onFailed();
- }
- return this;
- }
-
- public <T2> LuPromise<T2> map(final LuConverter<T, T2> converter)
- {
- final LuPromise<T2> promise = new LuPromise<>();
- then(new LuConsumer<T>() {
- @Override
- public void execute(T data) {
- promise.resolve(converter.convert(data));
- }
- }, getRejectConsumer());
- return promise;
- }
-
- public LuConsumer<LuPromiseError> getRejectConsumer()
- {
- return new LuConsumer<LuPromiseError>() {
- @Override
- public void execute(LuPromiseError error) {
- reject(error);
- }
- };
- }
-
- protected void onSuccess()
- {
- for (LuConsumer<T> c : _onSuccess) {
- if (c != null) {
- c.execute(_data);
- }
- }
- }
-
- protected void onFailed()
- {
- for (LuConsumer<LuPromiseError> c : _onFailed) {
- if (c != null) {
- c.execute(_error);
- }
- }
- }
- }
|