3 回答
TA贡献1898条经验 获得超8个赞
您可以使用viewModel实现来实现。喜欢,
public class UserViewModel extends AndroidViewModel {
private UserRepository userRepository;
private LiveData<List<UserData>> getUser;
public UserViewModel(@NonNull Application application) {
super(application);
userRepository = new UserRepository(application);
getUser= userRepository.getUser();
}
public LiveData<List<UserData>> getUser() {
return getUser;
}
}
创建此类后,请更新您的PersonalInfoActivity和LaunchActivity,
private UserViewModel userViewModel;
userViewModel.getUser().observe(this, new Observer<List<UserData>>() {
@Override
public void onChanged(@Nullable final List<UserData> user) {
//write code to set data of user to show using list of user
}
});
如果您对此有任何疑问,请离开commnet。
TA贡献1808条经验 获得超4个赞
我在本教程中创建了一个名为LivedataBus的库 。您可以像这样使用它:
//Subscribe
LiveDataBus.subscribe("event_name", this, Observer {
it.runAndConsume {
Toast.makeText(this, "Hello ${it.value}", Toast.LENGTH_LONG).show()
}
})
//Publish
val obj = SomeEvent()
LiveDataBus.publish("event_name", ConsumableEvent(value = obj))
神奇之处在于,我使用了ConsumableEvent,可以在触发事件后使用它,以防止从静态总线获取最新数据。
我在当前项目中使用了它,并且在多个活动和片段上都可以很好地工作。该库的好处是它可以在Livedata上运行,而您无需关心活动或片段生命周期。
添加回答
举报