lundi 3 octobre 2016

Android - Google's Contradiction on Singleton Pattern

I've been reading a bit about Singleton pattern usage in Android and it's disadvantages regarding to keeping the Context. In fact, when I implement the following code:

private static HttpManager sSingleton;
private Context mContext;

private HttpManager(Context context) {

    mContext = context;
}

public static synchronized HttpManager getInstance(Context context) {

    if (sSingleton == null) {
        sSingleton = new HttpManager(context);
    }

    return sSingleton;
}

Android Studio shows me the following warning:

Do not place Android context classes in static fields (static reference to HttpManager which has field mContext pointing to Context); this is a memory leak and also breaks Instant Run.

However, I can see Singletons implemented and recommended in this page of Android's docs.

If your application makes constant use of the network, it's probably most efficient to set up a single instance of RequestQueue that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality.

Since Google is contradicting itself, can someone guide me and advise me on this point? Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire