从回调中更新 class 字段

Updating class field from callback

我正在尝试使用 Retrofit 连接到 API。我需要登录用户,然后设置 "user" 字段,其中包含所有其他 api 调用所需的会话密钥。所以我需要在执行任何代码之前让它可用,但在设置此字段之前我不知道如何检查或阻止代码。任何想法如何去做?

public class ApiClient {

public static final String developerKey = "";
public static final String applicationKey = "";

static final String BASE_URL =
        "https://secure.techfortesco.com/tescolabsapi";

public ApiService mApiService;
public User user;

public ApiClient() {
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel( RestAdapter.LogLevel.FULL )
            .setEndpoint( BASE_URL )
            .build();

    if(mApiService == null) {
        mApiService = restAdapter.create( ApiService.class );
    }
}

public void login() {

    mApiService.login( developerKey, applicationKey, new Callback<User>() {

        @Override
        public void success ( User user, Response response ) {
            //code which should update user field
        }

        @Override
        public  void failure ( RetrofitError error ) {

        }

    } );
}

public interface ApiService {

    @GET ("/restservice.aspx?command=LOGIN&email=&password=")
    public void login (
            @Query ("developerkey") String developerKey,
            @Query ("applicationkey") String applicationKey,
            Callback<User> callback );

    @GET ("/restservice.aspx?command=PRODUCTSEARCH")
    public void search (
            @Query ("searchtext") String searchText,
            @Query ("sessionkey") String sessionKey,
            Callback<Pojo.SearchResult> callback);
}
}

您可以尝试使用回调:

示例:

public interface LoginCallback {
    void ready();
}

并在 Activity/片段

public MainActivity extends Activity {

    public void onCreate() {
        super.onCreate();
        ApiClient client = new ApiClient();
        client.login(new LoginCallback() {
            @Override
            public void ready() {
            //... do your next request in the API.
            }
        });
    }    
}

您的登录方式变为:

public void login(final LoginCallback loginCallback) {

 mApiService.login( developerKey, applicationKey, new Callback<User>() {

    @Override
    public void success ( User user, Response response ) {
        //code which should update user field
        loginCallback.ready();
    }

    @Override
    public  void failure ( RetrofitError error ) {

    }

} );

}