在多个活动中将LiveData替换为EventBus

目前,我的项目使用EventBus发布事件,而我正在尝试用EventBus替换LiveData。从理论上讲,它们的工作方式相似。我一开始就毫不费力地迁移了。但这是我不知道如何处理的情况。


这是场景。


LaunchActivity-> PersonInfoActivity-> UpdateInfoActivity


当前,我们使用EventBus在LaunchActivity和PersonInfoActivity中订阅UserInfoEvent


LaunchActivity.java


public class LaunchActivity{

     @Subscribe(threadMode = ThreadMode.MAIN)

     public void onEvent(UserInfoEvent event){


     }

}

PersonInfoActivity.java


public class PersonInfoActivity{

     @Subscribe(threadMode = ThreadMode.MAIN)

     public void onEvent(UserInfoEvent event){


     }

}

UpdateInfoActivity.java


public class UpdateInfoActivity{

     public void onSubmit(){

          EventBus.getDefault().post(new UserInfoEvent());

     }

}

问题是,我想用LiveData代替这种情况


我做了什么?


我已经阅读了有关livedata Room的单例用法的问题-更新数据库时,LiveData观察器不会触发,我想尝试使用相同的方式,但是没有运气。每当onChanged()我开始活动时,事件都会触发


郎朗坤
浏览 334回答 3
3回答

汪汪一只猫

您可以使用viewModel实现来实现。喜欢,public class UserViewModel extends AndroidViewModel {private UserRepository userRepository;private LiveData<List<UserData>> getUser;public UserViewModel(@NonNull Application application) {&nbsp; &nbsp; super(application);&nbsp; &nbsp; userRepository = new UserRepository(application);&nbsp; &nbsp; getUser= userRepository.getUser();}public LiveData<List<UserData>> getUser() {&nbsp; &nbsp; return getUser;}}创建此类后,请更新您的PersonalInfoActivity和LaunchActivity,private UserViewModel userViewModel;&nbsp; &nbsp; userViewModel.getUser().observe(this, new Observer<List<UserData>>() {&nbsp; &nbsp; @Overridepublic void onChanged(@Nullable final List<UserData> user) {//write code to set data of user to show using list of user}});如果您对此有任何疑问,请离开commnet。

RISEBY

我认为对LiveData有一些误解。你可以在这里看看它可能会对您有所帮助。此外,您还可以使用LiveData和LiveData事件总线来检查此事件总线的实现。希望能帮助到你!!!

炎炎设计

我在本教程中创建了一个名为LivedataBus的库 。您可以像这样使用它:&nbsp;//Subscribe&nbsp;LiveDataBus.subscribe("event_name", this, Observer {&nbsp; &nbsp; &nbsp; &nbsp; it.runAndConsume {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Toast.makeText(this, "Hello ${it.value}", Toast.LENGTH_LONG).show()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp;//Publish&nbsp;val obj = SomeEvent()&nbsp;LiveDataBus.publish("event_name", ConsumableEvent(value = obj))神奇之处在于,我使用了ConsumableEvent,可以在触发事件后使用它,以防止从静态总线获取最新数据。我在当前项目中使用了它,并且在多个活动和片段上都可以很好地工作。该库的好处是它可以在Livedata上运行,而您无需关心活动或片段生命周期。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java