我有一个android项目,正在使用wait()和notify(),所以某些代码只在后台任务之后执行,这是一个调用firebase的函数:
//Code Snippet 1
public Task<String> checkIfJokeSavedFirebase() throws InterruptedException {
final String[] idToken = {""};
Map<String, Object> data = new HashMap<>();
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
mUser.getIdToken(true)
.addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
public void onComplete(@NonNull Task<GetTokenResult> task) {
if (task.isSuccessful()) {
idToken[0] = task.getResult().getToken();
data.put("token", idToken[0]);
String someObject = "test";
synchronized (someObject) {
Log.d("longdebug","someObject pre notify");
someObject.notify();
}
//notify();
// Send token to your backend via HTTPS
// ...
} else {
// Handle error -> task.getException();
}
}
});
String someObject = "test";
synchronized (someObject){
Log.d("longdebug","someObject pre wait");
someObject.wait();
}
Log.d("runtimeexception","pre actually called");
data.put("token", idToken[0]);
//data.put("jokeid",jokeJSON.getString("id"));
return FirebaseFunctions.getInstance()
.getHttpsCallable("checkIfJokeSaved")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>() {
@Override
public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
Log.d("runtimeexception",".then");
HashMap result = (HashMap) task.getResult().getData();
JSONObject res = new JSONObject(result);
String jokeStored = res.getString("jokeStored");
Log.d("runtimeexception","jokeStored returned");
return jokeStored;
}
});
}以及我调用函数的代码::
//Code Snippet 2
try {
Log.d("runtimeexception","pre checkSavedCall");
activity.checkIfJokeSavedFirebase().addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
Log.d("runtimeexception","pre task.getResult");
Log.d("runtimeexception","task.getResult:" + task.getResult());
jokeSaved = Boolean.parseBoolean(task.getResult());
String synchronizedChannel = "displaysaved";
synchronized (synchronizedChannel){
Log.d("runtimeexception","pre notify");
synchronizedChannel.notifyAll();
}
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
String synchronizedChannel = "displaysaved";
synchronized (synchronizedChannel){
try {
Log.d("runtimeexception","pre wait");
synchronizedChannel.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}我的代码没有写入代码片段1中的".then“日志,但是当我删除:
synchronized (synchronizedChannel){
try {
Log.d("runtimeexception","pre wait");
synchronizedChannel.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}从snippet 2开始,snippet 1进入".then“日志并完成执行。删除wait()语句怎么可能导致对firebase函数的调用结束?
发布于 2020-08-12 06:51:31
我没有找到同步问题的解决方案,但我只是从AsyncTask切换到RxJava,并将Firebase调用转移到一个任务,这允许我摆脱所有以前的同步语句,并且只需要在任务中使用两个同步语句。
https://stackoverflow.com/questions/63293216
复制相似问题