Java Android MVVM - 如何将变量从存储库发送回 activity?

Java Android MVVM - how to send a variable from Repository back to activity?

我可以在 onPostExecute 方法 中使用 ASynctask 获取 rowId 值,我正在尝试将值发送回 activity 这样它就可以存储并在以后使用 所以如何做到这一点。

Activity :

Note note = new Note(userId, therapistId, automaticThoughtString,  distortions, challengeThoughtString, alternativeThoughtString, postedWorkout);
             noteViewModel.insert(note).observe(WorkoutAutomaticThoughtActivity.this, new Observer<Long>() {
                @Override
                public void onChanged(Long cbtId) {

                    sqCbtId = cbtId;
                    Log.d(TAG, "AutomaticThought" + sqCbtId);
                }
            });

视图模型:

 public LiveData<Long> insert (Note note) {
    return repository.insert(note);  
} 

存储库:

    public MutableLiveData<Long> insert(Note note) {
    final MutableLiveData<Long> cbtId = new MutableLiveData<>();
    new InsertNoteAsyncTask(noteDao, cbtId).execute(note);
    return cbtId; 

异步:

 public InsertNoteAsyncTask(NoteDao noteDao, MutableLiveData<Long> cbtId) {
    this.noteDao = noteDao;
}

@Override
protected Void doInBackground(Note... notes) {
    sqCbtId = noteDao.insert(notes[0]);
    return null;
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    getCbtId(sqCbtId);
    Log.d(TAG, "onPostExecuteAsync: " + sqCbtId);
}

public void getCbtId(long cbtId) {
    sqCbtId = cbtId;
}

CbtId 在 log.d 中被正确捕获,但它没有发送回 activity。我觉得可能跟Async任务中的构造函数有关。

修改插入方式

public MutableLiveData<Long> insert(Note note) {
 final MutableLiveData<Long> id = new MutableLiveData<>();
 new InsertNoteAsyncTask(noteDao, id).execute(note); 
 return id;
}

修改InsertNoteAsyncTask构造并接收id。现在修改 onPostExecute 方法并设置 id

   class InsertNoteAsyncTask extends AsyncTask<Note, Void, Long> {
    private NoteDao noteDao;
    private MutableLiveData<Long> id;
     public InsertNoteAsyncTask(NoteDao noteDao, MutableLiveData<Long> id) {
        this.noteDao = noteDao;
        this.id = id;
     }

     @Override
     protected Long doInBackground(Note... notes) {
        long sqCbtId = noteDao.insert(notes[0]);
        return sqCbId;
     }

     @Override
     protected void onPostExecute(Long sqCbtId) {
        super.onPostExecute(result);
        id.setValue(sqCbtId); 
        Log.d(TAG, "onPostExecuteAsync: " + sqCbtId);
     }
    }

现在在 ViewModel return 中观察 Mu​​tableLiveData 并在 Activity 中观察它。例如:

public LiveData<Long> insertNote(Note note) {
  return noteRepository.insert(note);
}

现在Activity,你可以观察LiveData中的变化:

viewModel.insertNote(Note).observe(this,
        new Observer<Long>() {
          @Override
          public void onChanged(Long id) {
            // do whatever you want with the id
          }
        });