使用共享ViewModel将FireStore数据分成两个片段的有效方法



上下文:我有一个User类,看起来像这样:

public class User {
private String firstname;
private String lastname;
private GeoPoint location;

/* Constructor and getters */
...
}

和两个Fragment,其中我将在第一个片段中显示用户名称列表,使用RecyclerViewGoogleMap显示第二个片段中用户的设备位置标记。我在这两个片段之间使用共享的ViewModel来提供所需的数据。ViewModel看起来像这样:

@HiltViewModel
public class UsersViewModel extends ViewModel {
private List<User> users;
private UserRepository repository;
@Inject
public UsersViewModel(UserRepository repository) {
this.repository = repository;
}
public void fetchUsers(OnFetchDataCallback callback) {
repository.getUsers(callback); 
}
public void setUsers(List<User> users) {
this.users = users;
}
public List<User> getUsers() {
return users;
}
}

在我的存储库类中,

public class UserRepository {
private final FirebaseFirestore db;
@Inject
public UserRepository(FirebaseFirestore db) {
this.db = db;
}
public List<User> getUsers(OnFetchDataCallback callback) {
db.collection("users")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot val,
@FirebaseFirestoreException e) {
List<User> users = new ArrayList<>();

for (QueryDocumentSnapshot document : val) {
users.add(document.toObject(User.class);
}
callback.onFetchData(users);
}
});
}
}

我有一个叫做getUsers()的方法,它将从firestore数据库中实际获取用户。我还创建了一个接口回调,如下所示

public interface OnFetchDataCallback {
void onFetchData(List<User> users);
}

以便稍后我可以访问我的两个片段中获取的用户。在第一个片段中,

@AndroidEntryPoint
public class DisplayUsersFragment extends Fragment {
private FragmentDisplayUsersBinding binding;
private UsersViewModel viewModel;
private UsersAdapter adapter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = new ViewModelProvider(this).get(UsersViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentDisplayUsersBinding.inflate(inflater, container, false);
binding.usersRecyclerView.setLayoutManager(
new LinearLayoutManager(getContext()));
viewModel.fetchUsers(new OnFetchDataCallback() {
@Override
public void onFetchData(List<User> users) {
viewModel.setUsers(users);
adapter = new UsersAdapter(viewModel.getUsers());
binding.usersRecyclerView.setAdapter(adapter);
}
});
return binding.getRoot();
}
}

我调用fetchUsers()并在回调中访问usersList,并在为RecyclerView构造适配器之前将其设置为viewModelusers,并通过调用viewModel.getUsers()并将其作为适配器的构造函数参数传递给它提供所需的数据。现在,我的问题是在第二个片段中,

@AndroidEntryPoint
public class UsersMapFragment extends Fragment implements OnMapReadyCallback {
private FragmentUsersMapBinding binding;
private UsersViewModel viewModel;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewModel = new ViewModelProvider(this).get(UsersViewModel.class);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
binding = FragmentUsersMapBinding.inflate(inflater, container, false);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view,
@Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment = SupportMapFragment.newInstance();
getChildFragmentManager().beginTransaction()
.add(R.id.users_map_fragment_container, mapFragment)
.commit()
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
viewModel.fetchUsers(new OnFetchDataCallback() {
@Override
public void onFetchData(List<User> users) {
viewModel.setUsers(users);
for (User user : viewModel.getUsers()) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(
user.getLocation().getLatitude(),
user.getLocation().getLongitude())
)
.title(user.getFirstname() + " " 
user.getLastname()
)
);
}
}
});
}
}

我在onMapReady()中再次调用fetchUsers(),这样我就可以在它的回调中访问用户并使用它们在地图中创建标记。从本质上讲,我试图调用fetchUsers()两次,但我认为有一个更有效的方法来做到这一点,但我不知道如何处理这个。请帮助我,对不起,我的英语不好。

你可以在ViewModel中使用实时数据:参见下面给出的代码:

@HiltViewModel
public class UsersViewModel extends ViewModel {
private List<User> users;
MutableLiveData<List<User>> usersLiveData = new MutableLiveData();
private UserRepository repository;
@Inject
public UsersViewModel(UserRepository repository) {
this.repository = repository;
}
public void fetchUsers() {
repository.getUsers(new OnFetchDataCallback() {
@Override
public void onFetchData(List<User> users) {
usersLiveData.setValue(users);
// you can observe this data after calling fetch users from your activity
setUsers(users);
}); 
}
public void setUsers(List<User> users) {
this.users = users;
}
public List<User> getUsers() {
return users;
}
}

活动中:

mViewModel.fetchUsers();

在两个片段中:

viewModel.usersLiveData.observe(this,{ list->
// user your list here in both fragments
// rather than fetch users on both fragments
});

相关内容

  • 没有找到相关文章

最新更新