java等待观察者完成

时间:2020-02-09 06:48:52

标签: java asynchronous observable

我对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对象。如果有其他选择,请告诉我。 > << / p>

1 个答案:

答案 0 :(得分:0)

首先创建一个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");