问题:
我有一些活动,在屏幕中间有共享按钮,共享标题,共享过程栏和容器,其中片段被替换了。
所以我有活动的viewmodel-ActivityViewModel 在它的内部有以下观测值:
val mNavigationToMainActivity = CompletableSubject.create()
val mNavigationToUsername = PublishSubject.create<Any>()
val mNavigationToPassword = PublishSubject.create<Any>()
val mNavigationToChangePassword = PublishSubject.create<LoginItem>()
val mProcessBar = PublishSubject.create<Int>()
val mContinueButtonEnabled = BehaviorSubject.createDefault(false)
val mContinueClick = PublishSubject.create<Any>()
val mChangeTitleSubject = BehaviorSubject.createDefault(false)
val mLoadingIndicatorSubject = BehaviorSubject.createDefault(false)
,在片段之间有共享的viewmodel,它调用FragmentViewModel。 所有片段都使用相同的视图模型
现在的问题是片段的视图模型如何访问活动的视图模型? 例如,当用户单击“登录”按钮时,我希望fragmentviewmodel可以访问活动的加载程序,然后可以访问Navigationtonext屏幕。
或者例如在验证输入时启用按钮
这就是我在这些之间进行通信的目的:
fun <T> PublishSubject<T>.bind(subject: PublishSubject<T>): Disposable {
return subscribe({ subject.onNext(it) }, { throwable -> subject.onError(throwable) })
}
fun <T> BehaviorSubject<T>.bind(subject: BehaviorSubject<T>): Disposable {
return subscribe({ subject.onNext(it) }, { throwable -> subject.onError(throwable) })
}
fun CompletableSubject.bind(subject: CompletableSubject): Disposable {
return subscribe({ subject.onComplete() }, { throwable -> subject.onError(throwable) })
}
我让片段的视图模型扩展基本视图模型的活动性视图模型
所以这是敏捷的视图模型
打开类IntroViewModel:BaseViewModel(){
val mNavigationToMainActivity = CompletableSubject.create()
val mNavigationToUsername = PublishSubject.create<Any>()
val mNavigationToPassword = PublishSubject.create<Any>()
val mNavigationToChangePassword = PublishSubject.create<LoginItem>()
val mProcessBar = PublishSubject.create<Int>()
val mContinueButtonEnabled = BehaviorSubject.createDefault(false)
val mContinueClick = PublishSubject.create<Any>()
val mChangeTitleSubject = BehaviorSubject.createDefault(false)
fun bind(introViewModel: IntroViewModel){
mNavigationToUsername.bind(introViewModel.mNavigationToUsername).addDisposable()
mNavigationToPassword.bind(introViewModel.mNavigationToPassword).addDisposable()
mNavigationToChangePassword.bind(introViewModel.mNavigationToChangePassword).addDisposable()
mNavigationToMainActivity.bind(introViewModel.mNavigationToMainActivity).addDisposable()
mProcessBar.bind(introViewModel.mProcessBar).addDisposable()
mContinueButtonEnabled.bind(introViewModel.mContinueButtonEnabled).addDisposable()
}
fun continueClicked() {
mContinueClick.onNext(Any())
}
} 这是片段
class ChangePasswordViewModel(private val userRepository: UserRepository)
: IntroViewModel() {
在每个片段的内部,我将活动的视图模型绑定到该片段的视图模型
viewModel = ViewModelProviders.of(activity!!, viewModelFactory).get(ChangePasswordViewModel::class.java)
viewModel.start(2,arguments?.getParcelable(LoginItem::class.simpleName))
ViewModelProviders.of(activity!!, viewModelFactory).get(IntroViewModel::class.java).apply {
viewModel.bind(this)
}
讨厌,我真的不喜欢。 你能帮我吗?