MVVM (매우 새로운 기능)을 찾으려고 노력하고 있으며 Room 및 ViewModel을 사용하여 LiveData를 관찰하는 방법을 알아 냈습니다. 이제 문제가 있습니다.
매개 변수가 필요한 Room 쿼리가 있는데 이것이 MainActivity의 onCreate에서 LiveData 관찰을 시작하는 방법입니다.
String color = "red";
myViewModel.getAllCars(color).observe(this, new Observer<List<Car>>() {
@Override
public void onChanged(@Nullable List<Car> cars) {
adapter.setCars(cars);
}
});
이 코드를 사용하여 "빨간색"자동차 목록을 받고 RecyclerView를 목록으로 채 웁니다.
이제 내 질문에-
color
를 변경하는 방법이 있습니까
getAllCars
내부 변수
방법 (예 : 버튼 클릭)으로 관찰자가 새로운 목록을 반환하도록 영향을 줍니까? 색상 변수 만 변경해도 아무런 변화가 없습니다.
- 답변 # 1
- 답변 # 2
@dglozano 답변 이외의 쉬운 방법은
mRepository.getCarsByColor(c))
를 관찰하는 것입니다.color
를 관찰하는 대신 . 그리고list
에 와이즈 비츠 새 목록을 가져옵니다.예 :
valueChange
에서 수업이 이러다color
ViewModel
에서 이것을해라 :MutableLiveData<String> myColor = new MutableLiveData<String>();
참고: 1.
Activity
button.setOnClickListener(new OnClickListener() { public void onClick(View v) { myViewModel.myColor.setValue("newColor"); } }); myViewModel.myColor.observe(this, new Observer<String>() { @Override public void onChanged(@Nullable String newValue) { // do this on dedicated thread List<Car> updateList = myViewModel.getCarsByColor(newValue) // update the RecyclerView } });
로 포장 할 필요가 없습니다 .getCarsByColor()
의 방법LiveData
를 반환 할 수 있습니다Dao
대신 .2. 메인 스레드에서 db 쿼리를 실행하지 말고
List<Cars>
를 호출하십시오. RecyclerView를 새로 고침합니다.LiveData<List<Cars>>
관련 자료
- java - CreateView에서 조각을 추가하는 동안 Inflate 메서드를 확인할 수 없습니다
- javascript - 이 변경 방법을 어떻게 작성하여 주어진 금액에 대한 청구서를 받음
- c# - 단일 매개 변수로 호출 할 때 선택적 매개 변수가있는 메서드 대리자가 작동하지 않음
- Python에서 재귀 메서드의 기본 매개 변수로 set 사용
- javascript - join () 메서드를 Mathpow에 연결하여 배열을 다시 정수로 변경할 수 없습니다
- c - 재귀를 while 루프 문으로 변경하는 방법 (즉, 반복)
- 분리 된 div에 마우스를 올려 놓는 동안 Javascript로 범위의 텍스트 색상 변경
- c# - 문자열 매개 변수가있는 Action을없는 메소드로 전달
- pandas - Python cut 메서드를 사용하여 저장소를 만들고 하나의 매개 변수를 수락하고 적절한 저장소를 반환하는 방법은 무엇입니까?
- unity - Update 내부에서 while 루프가 없거나 대신 코 루틴을 사용하지 않도록 스크립트를 어떻게 변경할 수 있습니까?
- android studio - "광고 구성 없음" onAdFailedToLoad () 메소드에서 광고를로드하는 중
- javascript - 스크롤하는 동안 수직 메뉴의 크기를 변경하는 방법
- while 루프에서 Bash 변경 변수 값
- Android에서 Firebase로 비밀번호를 변경하는 동안 애플리케이션이 충돌했습니다
- python - QLayout을 초기화하기 위해 매개 변수 목록에 "self"를 전달하면 setLayout () 메서드 호출을 건너 뛸 수 있습니까?
- asp.net - ActionResult 메서드가 뷰 내부에서 HtmlBeginForm ()에서 매개 변수를 사용하지 않는 이유는 무엇입니까?
- python - for 루프를 while 루프로 변경하는 방법
- Xdebug v3에서 단계 디버깅 중에 중단 점을 변경하면 nginx 502 Bad Gateway가 발생합니다
- scala3 확장 메서드 유형 매개 변수
- unity3d - 애니메이터 매개 변수는 Unity2D를 변경하지 않습니다
- OpenCv의 폴더에서 여러 이미지 읽기 (python)
- 파이썬 셀레늄 모든 "href"속성 가져 오기
- html - 자바 스크립트 - 클릭 후 변경 버튼 텍스트 변경
- git commit - 자식 - 로컬 커밋 된 파일에 대한 변경을 취소하는 방법
- javascript - 현재 URL에서 특정 div 만 새로 고침/새로 고침
- JSP에 대한 클래스를 컴파일 할 수 없습니다
- jquery - JavaScript로 현재 세션 값을 얻으시겠습니까?
- JavaScript 변수를 HTML div에 '출력'하는 방법
- javascript - swiperjs에서 정지, 재생 버튼 추가
- python - 문자열에서 특정 문자 제거
이 답변에서 언급했듯이 귀하의 솔루션은
Transformation.switchMap
입니다.Android for Developers 웹 사이트 :
와이즈 비즈여러분의 상황에서는 다음과 같이 보일 것입니다 :
따라서
public class CarsViewModel extends ViewModel { private CarRepository mRepository; private LiveData<List<Car>> mAllCars; private LiveData<List<Car>> mCarsFilteredByColor; private MutableLiveData<String> filterColor = new MutableLiveData<String>(); public CarsViewModel (CarRepository carRepository) { super(application); mRepository = carRepository; mAllCars = mRepository.getAllCars(); mCarsFilteredByColor = Transformations.switchMap(filterColor, c -> mRepository.getCarsByColor(c)); } LiveData<List<Car>> getCarsFilteredByColor() { return mCarsFilteredByColor; } // When you call this function to set a different color, it triggers the new search void setFilter(String color) { filterColor.setValue(color); } LiveData<List<Car>>> getAllCars() { return mAllCars; } }
를 부르면 필터 색상 LiveData를 변경하면setFilter
를 호출하는 Transformation.switchMap을 심사합니다. 그런 다음 쿼리 결과로 mCarsFilteredByColor LiveData를 업데이트하십시오. 따라서보기에서이 목록을 관찰하고 다른 색상을 설정하면 관찰자는 새 데이터를받습니다.작동하는지 알려주세요.