Last active
March 13, 2017 06:09
-
-
Save kamikat/42b218017db6e42deba327c2f7e9a32a to your computer and use it in GitHub Desktop.
Singleton observable query parameter storage... in RxJava...
This file contains hidden or 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 QueryDefaults { | |
private static QueryDefaults _Instance; | |
public static synchronized QueryDefaults getInstance() { | |
if (_Instance == null) { | |
_Instance = new QueryDefaults(); | |
} | |
return _Instance; | |
} | |
public static Observable<Map<String, String>> create() { | |
return getInstance().createInternal(); | |
} | |
public static Action1<String> putQueryParameter(String key) { | |
return value -> getInstance().put(key, value); | |
} | |
public static void removeQueryParameter(String key) { | |
getInstance().remove(key); | |
} | |
final Map<String, String> mQueryParameters = new HashMap<>(); | |
final List<Subscriber<? super Map<String, String>>> mSubscriber = new ArrayList<>(); | |
private Observable<Map<String, String>> createInternal() { | |
ArrayList<Subscriber<? super Map<String, String>>> subscriberRef = new ArrayList<>(); | |
Observable<Map<String, String>> observable = Observable.create(subscriber -> { | |
subscriber.onNext(mQueryParameters); | |
mSubscriber.add(subscriber); | |
subscriberRef.add(subscriber); | |
}); | |
// FIXME should clean all subscriber even if on which `unsubscribe()` is not called. | |
// FIXME It's safe for observable with single subscriber but... | |
return observable.doOnUnsubscribe(() -> { | |
mSubscriber.removeAll(subscriberRef); | |
subscriberRef.clear(); | |
}); | |
} | |
public synchronized void put(String key, String value) { | |
mQueryParameters.put(key, value); | |
dispatchNext(); | |
} | |
public synchronized void remove(String key) { | |
mQueryParameters.remove(key); | |
dispatchNext(); | |
} | |
private void dispatchNext() { | |
for (Subscriber<? super Map<String, String>> subscriber : mSubscriber) { | |
subscriber.onNext(mQueryParameters); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment