Robospice - Addlistenerifpending - How Do I Know If Request Was Found?
Solution 1:
Ok, in case google leads anyone here. Proper solution: in reality, this functionality is already in the library. There is a method which gets called when pending request WAS found, it just does... nothing.
You need to:
Create your own interface extending
PendingRequestListener
:publicinterfaceMyPendingRequestListener<T> extendsPendingRequestListener<T> { voidonRequestAggregated(); }
Note: you will need to use request listeneres implementing this interface when doing requests through Robospice.
Create your own class implementing
RequestListenerNotifier
. I did this by copy-pastingDefaultRequestListenerNotifier
(I was not able to extend it because methodpost(..)
is private) because it contains porper notification implementation for other cases. For example,MyRequestListenerNotifier
.Override method
notifyListenersOfRequestAggregated
:@Overridepublic <T> voidnotifyListenersOfRequestAggregated(final CachedSpiceRequest<T> request, Set<RequestListener<?>> listeners) { post(newAggregatedRunnable(listeners), request.getRequestCacheKey()); } privatestaticclassAggregatedRunnableimplementsRunnable { privatefinal Set<RequestListener<?>> listeners; publicAggregatedRunnable(final Set<RequestListener<?>> listeners) { this.listeners = listeners; } @Overridepublicvoidrun() { if (listeners == null) { return; } Ln.v("Notifying " + listeners.size() + " listeners of request aggregated"); synchronized (listeners) { for (final RequestListener<?> listener : listeners) { if (listener != null && listener instanceof MyPendingRequestListener) { Ln.v("Notifying %s", listener.getClass().getSimpleName()); ((MyPendingRequestListener<?>) listener).onRequestAggregated(); } } } } }
Extend SpiceService and override the following method (you will need to use this customized service instead of standard robospice service):
protected RequestListenerNotifier createRequestRequestListenerNotifier() { returnnew MyRequestListenerNotifier(); }
That's it. Now, when you use addListenerIfPending
, onRequestAggregated()
will be called when pending request IS found.
IMPORTANT NOTE: This will only work when you use Cache key when doing request. For example, you can use empty string (but NOT null) as cache key.
Example:
//doing request for the first time
spiceManager.execute(request, "", DurationInMillis.ALWAYS_EXPIRED, requestListener);
//... //checking if request is pending e.g. when activity is restarted
spiceManager.addListenerIfPending(responseClass, "", requestListener);
Post a Comment for "Robospice - Addlistenerifpending - How Do I Know If Request Was Found?"