我正在尝试在应用程序中实现 ViewModel,该应用程序使用 FirestorepagingAdapter 从 Firestore 获取一些数据,并将其显示在 recyclerview 中。我已经获取所有数据并显示它,但仍然没有使用 ViewModel,它都在 MainActivity
我正在尝试将创建 Firestorepagingoptions 的代码移动到视图模型,并在我的 MainActivity 中,只需创建适配器并设置为 recyclerview。但是 FirestorePagingOptions.Builder 需要设置一个 LifecycleOwner 而我不知道如何在我的 ViewModel 中获取它,或者我根本不应该在 ViewModel 上这样做,我对这些 ViewModel 很迷茫,所以如果有人有任何建议,我将不胜感激。非常感谢。
这是我在 MainActivity 上的原始代码(尚未更改以从 Viewmodel 获取数据)
public class ListaEmpresasActivity extends AppCompatActivity {
private FirebaseFirestore firebaseDB;
private RecyclerView recyclerViewListaEmpresas;
private FirestorePagingAdapter adapter;
private boolean viewChanged;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_empresas);
recyclerViewListaEmpresas = findViewById(R.id.activity_main_lista_empresas);
firebaseDB = FirebaseFirestore.getInstance();
FirestorePagingOptions<EmpresaLista> options = configuraPaginacaoInicial();
adapter = new ListaEmpresasAdapter(options);
configuraRecyclerView(adapter);
}
private FirestorePagingOptions<EmpresaLista> configuraPaginacaoInicial() {
Query query = firebaseDB.collection("Lista_Empresas").orderBy("id");
return configuraOpcoesPaginacao(query);
}
private FirestorePagingOptions<EmpresaLista> configuraOpcoesPaginacao(Query query) {
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(10)
.setPageSize(20)
.build();
return new FirestorePagingOptions.Builder<EmpresaLista>()
.setLifecycleOwner(this)
.setQuery(query, config, EmpresaLista.class)
.build();
}
private void configuraRecyclerView(FirestorePagingAdapter adapter) {
recyclerViewListaEmpresas.setHasFixedSize(true);
recyclerViewListaEmpresas.setLayoutManager(new LinearLayoutManager(this));
recyclerViewListaEmpresas.setAdapter(this.adapter);
}
还有我的 ViewModel 上的代码
public class ListaEmpresasViewModel extends ViewModel {
private MutableLiveData<FirestorePagingOptions<EmpresaLista>> options;
private FirebaseFirestore firebaseDB;
public LiveData<FirestorePagingOptions<EmpresaLista>> getOptions() {
firebaseDB = FirebaseFirestore.getInstance();
options = configuraPaginacaoInicial();
return options;
}
private MutableLiveData<FirestorePagingOptions<EmpresaLista>> configuraPaginacaoInicial() {
Query query = firebaseDB.collection("Lista_Empresas").orderBy("id");
return configuraOpcoesPaginacao(query);
}
private MutableLiveData<FirestorePagingOptions<EmpresaLista>> configuraOpcoesPaginacao(Query query) {
PagedList.Config config = new PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPrefetchDistance(10)
.setPageSize(20)
.build();
return new FirestorePagingOptions.Builder<EmpresaLista>()
.setLifecycleOwner()
.setQuery(query, config, EmpresaLista.class)
.build();
}
}