androidactivity-lifecyclerobospice

RoboSpice requests results when user taps home button


We are using Robospice 1.4.12 with okhttp. Everything is working fine except getting the results from a request when user taps home button and then comes back to the activity.

Example: we fire a request and then press home button and we wait for request to finish, when we come back to the activity the listener never gets notified. If we come back before the request finishes everything works ok.

Orientation changes are working fine. We are using LruCacheObjectPersister for in memory cache.

Now some code:

Our service:

public class MyService extends OkHttpSpiceService {

    @Override
    public CacheManager createCacheManager(Application application) throws CacheCreationException {
        CacheManager cacheManager = new CacheManager();
        int cacheSize = 1 * 1024 * 1024; // 1MiB
        cacheManager.addPersister(new LruCacheObjectPersister<LoginModel>(LoginModel.class,
                new LruCache<Object, CacheItem<LoginModel>>(cacheSize)));
        return cacheManager;
    }

}

Our onStart in the fragment:

@Override
    public void onStart() {
        super.onStart();
            //spice manager gets started in base fragment
        spiceManager.addListenerIfPending(LoginModel.class, REQUEST_KEY, new LoginRequestListener());
    }

Request Execution:

spiceManager.execute(new LoginRequest(), REQUEST_KEY, DurationInMillis.ONE_DAY,
                        new LoginRequestListener());

Are we missing something?


Solution

  • This how RS works. You have to understand that, on Android, you can never get sure that the activity before pressing home and after getting back are the same instance. Meanwhile, android can garbage collect your activity. And yes, this happens !!

    So, what RS does is that it executes queries in a different context to get sure that the launching request context will live long enough to execute the request. Which is not the case with an activity.

    That being said, if you want to reconnect to a pending request, look a spice manager methods. You will see a addListenerIfPending something method. That's the way to do it. RS also let's you check if such a pending request exists. You can also check if the cache contains your data already, etc, etc.