vendredi 22 juillet 2016

Design Pattern for Callbacks OPTIONALLY on UI Thread

I'm designing an API that makes heavy use asynchronous code-completion blocks.

public interface IResult<T extends Result.I> {
    void onResult(T);
}

public void doXYZ(IResult<Result.TypeA> iResult) { ... }

This API is for Android, where many (but not all) times, the user may want do do something in the onResult() callback that affects UI elements, thus necessitating that their code runs on the UI thread. Rather than burden the user with having to dirty up their code with runOnUIThread(...) invocations, I'm wondering if folks know of a design pattern that will make it easy, at the time of the doXYZ() invocation, for the user to specify whether the callback is to be called on their UI thread.

  1. For performance reason, I'd rather not force that my API always call onResult() on the UI thread.

  2. One pattern I've seen is add a method parameter: doXYZ(... , boolean callOnUIThread). However, since the API is documented, I'd rather not dirty up the documentation (and method signature) by having all those additional booleans.

  3. Another thought was to overload each doXYZ(), to have one with and one without the callOnUIThread parameter, but that's incredibly bad for documentation because of the bloat.

  4. Another thought I had was to add a onResultUI() method to IResult, in addition to onResult(), but that dirties up the user's code by having them have to always define both in their anonymous classes.

Any suggestions on a clean way to accomplish this that's: i. concise ii. great for code readability iii. easy on documentation ?

Aucun commentaire:

Enregistrer un commentaire