我使用的库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