[英]How can I wait until all FCM subscriptions are done
I fetch the server and get an array with topics to subscribe to, I loop it and subscribe to each topic, What I want to do is wait for this to complete then start new activity.我获取服务器并获得一个包含要订阅的主题的数组,我循环它并订阅每个主题,我想做的是等待它完成然后开始新的活动。
I did it with number of loop, If it equals the length minus one of array then start new activity.我用循环数做了它,如果它等于长度减去数组之一然后开始新的活动。 Here is my code:
这是我的代码:
int length = subscribeTo.length();
for (int i = 0; i < length; i++) {
String sub = null;
try {
sub = subscribeTo.get(i).toString();
} catch (JSONException e) {
e.printStackTrace();
}
int finalI = i;
JSONObject finalData = data;
String finalSub = sub;
FirebaseMessaging.getInstance().subscribeToTopic(sub).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Log.e("sub", finalSub);
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "can't login in", Toast.LENGTH_SHORT).show();
return;
}
Log.e("test", "sub" + finalI);
if (finalI == length - 1) {
try {
editor.putInt("sub_length", length);
editor.putString("restaurant_name", finalData.get("restaurant_name").toString());
editor.putString("username", finalData.get("username").toString());
editor.putString("password", finalData.get("password").toString());
editor.putString("sub" + finalI, finalSub);
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
editor.apply();
finish();
}
}
});
}
There is no better way to do?有没有更好的办法呢? I'm new to java by the way.
顺便说一下,我是 java 的新手。
No one seems to have responded Whatever it is, I searched a lot and here is how I solved it Using CountDownLatch
似乎没有人回应不管它是什么,我搜索了很多,这就是我使用
CountDownLatch
解决它的方法
The code:代码:
int length = subscribeTo.length();
CountDownLatch latch = new CountDownLatch(length);
for (int i = 0; i < length; i++) {
String sub = null;
try {
sub = subscribeTo.get(i).toString();
} catch (JSONException e) {
e.printStackTrace();
}
int finalI = i;
String finalSub = sub;
FirebaseMessaging.getInstance().subscribeToTopic(subscribeTo.get(i).toString())
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
editor.putString("sub" + finalI, finalSub);
latch.countDown(); // The number will decrease
}
});
}
latch.await(); // Here it will wait until it ensures that all subscriptions are completed
editor.putInt("sub_length", length);
editor.putString("restaurant_name", dataa.get("restaurant_name").toString());
editor.putString("username", dataa.get("username").toString());
editor.putString("password", dataa.get("password").toString());
editor.apply();
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
startActivity(intent);
Log.e("done", "yes");
SUIIII here: maybe u will see what you want SUIIII 在这里:也许你会看到你想要的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.