Android LiveData Observer未第二次触发

时间:2018-09-01 23:12:35

标签: android observable

我正在从事一项允许用户过滤搜索结果的活动。 最初,我获取所有数据,但是当用户想要过滤数据时,我需要调用另一个查询并更新视图。我为此使用Android ROOM和ViewModel。

问题在于,每次获取新数据时,都需要创建一个新的观察者,因为旧的观察者“停止”了。通常,这应该与一个观察者一起使用,每次更新数据时都会调用该观察者。您能帮我理解为什么会这样吗?

活动:

package com.jds.fitnessjunkiess.getfitapp.Activities.ExercisesView;

import android.arch.lifecycle.ViewModelProviders;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.jds.fitnessjunkiess.getfitapp.Activities.ExercisesView.Adapters.ExercisesAdapter;
import com.jds.fitnessjunkiess.getfitapp.Data.ViewModels.ExerciseViewModel;
import com.jds.fitnessjunkiess.getfitapp.R;

public class ExercisesViewActivity extends AppCompatActivity implements View.OnClickListener {

  private ExerciseViewModel exerciseViewModel;
  private ExercisesAdapter recyclerViewerAdapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_exercises_view);

    Toolbar toolbar = findViewById(R.id.toolbar_exercise_view_activity);
    toolbar.setTitle("Exercises");
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
      actionBar.setDisplayShowHomeEnabled(true);
    }

    RecyclerView recyclerView = findViewById(R.id.exercise_view_recycle_viewer);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);
    this.recyclerViewerAdapter = new ExercisesAdapter();
    recyclerView.setAdapter(recyclerViewerAdapter);

    this.exerciseViewModel = ViewModelProviders.of(this).get(ExerciseViewModel.class);
    this.exerciseViewModel.setFilters("", "");
//    this.exerciseViewModel.selectAll();
    this.exerciseViewModel.select().observe(this, exercises -> {
      if (exercises != null) {
        this.recyclerViewerAdapter.updateDataset(exercises);
      }
    });

    Button button = findViewById(R.id.test_button);
    button.setOnClickListener(this);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        onBackPressed();
        break;
    }

    return true;
  }

  @Override
  public void onClick(View v) {
    this.exerciseViewModel.setFilters("", "");
//    this.exerciseViewModel.select().observe(this, exercises -> {
//      if (exercises != null) {
//        this.recyclerViewerAdapter.updateDataset(exercises);
//      }
//    });
  }
}

查看模型:

public class ExerciseViewModel extends AndroidViewModel {
  ExercisesRepository repository;
  LiveData<List<Exercise>> data;

  public ExerciseViewModel(Application application) {
    super(application);
    this.repository = new ExercisesRepository(application);
  }

  public void setFilters(String muscleGroups, String type) {
    this.data = this.repository.filterSelect(muscleGroups, type);
  }

  public LiveData<List<Exercise>> select() {
    return data;
  }

  public void insert(Exercise exercise) {
    this.repository.insert(exercise);
  }
}

存储库

public class ExercisesRepository {
  private ExerciseDao dao;

  public ExercisesRepository(Application context) {
    WorkoutRoomDatabase database = WorkoutRoomDatabase.getDb(context);
    this.dao = database.exerciseDao();
  }

  public LiveData<List<Exercise>> filterSelect(String muscleGroups, String type) {
    return this.dao.filterSelect("%" + muscleGroups + "%", "%" + type + "%");
  }

  public void insert(Exercise exercise) {
    new insertAsyncTask(this.dao).execute(exercise);
  }

  private static class insertAsyncTask extends AsyncTask<Exercise, Void, Void> {

    private ExerciseDao exerciseDao;

    insertAsyncTask(ExerciseDao  dao) {
      exerciseDao = dao;
    }

    @Override
    protected Void doInBackground(final Exercise... params) {
      exerciseDao.insert(params[0]);
      return null;
    }
  }
}

DAO:

@Dao
public interface ExerciseDao {
  @Query("SELECT * FROM exercises WHERE muscleGroups LIKE :muscleGroup AND type LIKE :type")
  LiveData<List<Exercise>> filterSelect(String muscleGroup, String type);
  @Query("SELECT * FROM exercises")
  LiveData<List<Exercise>> selectAll();
  @Insert
  void insert(Exercise exercise);
  @Update
  void update(Exercise exercise);
  @Delete
  void delete(Exercise exercise);
  @Query("DELETE FROM exercises")
  void deleteAll();
}

4 个答案:

答案 0 :(得分:2)

您需要进行一些更改,因为您是在重新分配LiveData对象,而不是添加已过滤的项目。

您需要将 LiveData>数据更改为 MutableLiveData> ,并且需要在 setFilters 方法中从存储库获取数组列表并添加它使用setValue方法在MutableLiveData中。

ExerciseViewModel

 MutableLiveData<List<Exercise>> data = new MutableLiveData<>();


    public void setFilters(String muscleGroups, String type) {
        List<Exercise> ex = this.repository.filterSelect(muscleGroups, type).getValue();
        this.data.setValue(ex);
    }

希望对您有帮助。

答案 1 :(得分:0)

在setFilters方法中,您正在将一个新的实时数据重新分配给您拥有的实时数据实例。实时数据仅在其值被更改时才触发事件。因此,您可以使用可变的实时数据,并通过此类的setValue()设置其值。然后您的旁听者将被呼叫。

答案 2 :(得分:0)

当我通过单击按钮单击而在BottomSheetDialogFragament的onCreateView函数中调用时,两个观察者都被调用时,我面临着同样的问题。

private fun getKey() {
        if (ApiConstants.publicKey == null) {
            sendOTPViewModel.key.observe(viewLifecycleOwner, Observer { t ->
                if (t == ApiConstants.KEY_SUCCESS) {
                    getKey()
                }
            })

        } else {
            validateUser(number, from, BaseActivity.getDeviceId(mContext))
        }
    }

 private fun validateUser(loginId: String?, loginType: String?, deviceId: String?) {

        sendOTPViewModel.getValidateUser(loginId, loginType, deviceId).observe(viewLifecycleOwner, Observer { t ->
            LoggerUtils.E(TAG, t)
        })

    }

答案 3 :(得分:0)

Kotlin 答案

<块引用>

如果您正在使用,请删除函数中的这两点:

  1. = viewModelScope.launch { }
  2. 暂停