我使用的庫retrofit-2.1.0
Retrofit2異步回調不叫
public class UserManager {
private static final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MY_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
private static final UserService service = retrofit.create(UserService.class);
public static User getUserById(Integer userId) {
Call<User> call = service.getUser(userId);
final User[] user = new User[1];
final boolean[] isCalled = {false};
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
System.err.println("CALLED");
user[0] = response.body();
isCalled[0] = true;
}
@Override
public void onFailure(Call<User> call, Throwable t) {
isCalled[0] = true;
}
});
return user[0];
}
interface UserService {
@GET("users/{user_id}")
Call<User> getUser(@Path("user_id") Integer userId);
}
}
我從JUnit4測試調用它有這個非常簡單的代碼。
public class UserManagerTest {
@Test
public void testGetBattleById() throws Exception {
User user = UserManager.getUserById(1);
}
}
我User
類是罰款和GSON是能夠序列JSON
進去。網址也很好。
問題既不是onResponse
也不是onFailure
實際上被調用。 isCalled[0]
仍然false
,user[0]
仍然null
,我沒有看到任何stderr。
我GOOGLE了這個問題,發現了一些非常相似的情況,但不幸的是沒有真正的解決方案。我究竟做錯了什麼?
[這就是所謂的(http://ideone.com/PPHi95),但不那麼,你想... – Selvin
後調用權限,您無法返回用戶...它總是會返回null,因爲請求是異步的,並且你正在以同步的方式使用它 – Jaythaking