jeudi 22 septembre 2016

Can I and should I pass a Context to a static method outside of the UI?

I've looked around but never found a straightforward answer to this question. I'm wondering what would happen if I use a pattern that requires me to pass a Context to static methods to do things on the backend. For instance:

public static Observable<CreateThing> createNewThing(String thingName, Context context) { // Passing Context in
    return RestNetworker.handleResponse(ServiceGenerator.createService(Service.class).createThing(thingName))
            .doOnNext(response -> DatabaseHelper.getInstance(context).createThing(new Thing(response.getThingId(), thingName))); // context used to get instance of DatabaseHelper
}

This method makes an API call and then writes the object to the database locally after a success response. However, I need to pass a Context to create the instance of the database helper. I could alternatively pass the database helper itself, but then I'd be creating the instance (rather getting it, since it's singleton) in the Activity code and I'd rather not do that either.

My question really is: If, say, a user exits the Activity while the API call is in progress, will this Context instance get GC'd and result in an NPE when the response comes back? I've done this kind of thing before and never noticed that issue, but it really seems that there should be some consequence of doing this. I know that other developers must do some things off the UI thread that require a Context, so this should be a relatively easy question to answer.

Thanks guys! Please let me know if you need any more information to provide better context. Heh.

Aucun commentaire:

Enregistrer un commentaire