java等待观察者完成

zifan yan :

我对java异步功能很新,并且可以观察到所有这些。无论如何,在继续之前要确保异步函数返回吗?我当前正在使用Thread.sleep(100);以便可以获取所需的数据,但是我认为这不合适。

我的代码:

    private void getGroupAllInfo(CallbackContext callbackContext){
        Log.d("executing: ", "getGroupAllInfo1");
        Observable observable = GsscFactory.executeGetZwaveAllInfo(this.sock, MationPlugin.gatewayId, MationPlugin.account, MationPlugin.password);
        observable.subscribe(t -> {
            System.out.print(t);
            MationPlugin.allInfo.put("data",t.toString());
            // callbackContext.success(t.toString()); 


        });
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    this.getGroupAllInfo(callbackContext);
    try{
        Thread.sleep(100);
    }catch(InterruptedException e){
        e.printStackTrace();
    }
    callbackContext.success(this.allInfo.getString("data"));
}

我意识到我无法在observable.subscribe(t-> {})内分配变量,因此我决定将所需的数据放入json对象。如果有其他选择,请告诉我。> <

Yamin Mollah博士:

首先创建一个MutableLiveData变量,例如:

    MutableLiveData<String> response = new MutableLiveData<String>();

然后创建一个观察者,观察响应值的变化,例如:

    // Create the observer which updates the response when a new value arrives.
    final Observer<String> nameObserver = new Observer<String>() {
        @Override
        public void onChanged(@Nullable final String response) {
            // Update the UI like a TextView text or do whatever you want with your [response] value
            responseTextView.setText(response);
        }
    };

    // Observe the MutableLiveData, passing the observer.
    response.observe(this, nameObserver);

然后将新值发布到后台任务中的响应变量中,如下所示:

    response.postValue("response value");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章