java.lang.IllegalStateException: Cannot invoke observeForever on a background thread

前端 未结 3 615
梦谈多话
梦谈多话 2021-01-17 10:43

Can someone help me find where I am going wrong here. I need to continously observer network data and update the UI whenever there is a data change from the Worker. Please n

3条回答
  •  一生所求
    2021-01-17 10:57

    Additionally to the nice and detailled answer from @user1185087 here is a solution if you're using RxJava in your project. It's maybe not that short, but if you already use RxJava in your project, it's an elegant way to switch to the required thread (in this case the Android's UI thread via .observeOn(AndroidSchedulers.mainThread())).

    Observable.just(workManager.getStatusById(workRequest.getId()))
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(status -> status.observeForever(workStatus -> {
            // Handling result on UI thread
        }), err -> Log.e(TAG, err.getMessage(), err));
    

提交回复
热议问题