如何在多个片段内使用相同的viewModel方法?



我想使用一个viewModel和观察对象从一个方法。但是我不想在所有的片段中都写这个观察方法。只写在一个地方,使用其他片段。我想我需要片段扩展,但不能得到它如何做到这一点。我需要帮助。

我想使用的viewModel。

SharedViewModel.kt


class SharedViewModel @Inject constructor(private val notificationServiceRepo: NotificationServiceRepo) : ViewModel() {
private val _helpNotification = SingleLiveEvent<NetworkResult<BaseResponse<Any>>>()
val helpNotification get() = _helpNotification
fun postHelpNotification(helpNotificationRequest: HelpNotificationRequest) = viewModelScope.launch (
Dispatchers.IO){
_helpNotification.postValue(NetworkResult.Loading)
_helpNotification.postValue(notificationServiceRepo.postNotificationHelp(helpNotificationRequest))
}
}

这是调用方法和观察函数:

MainFragment.kt

viewModel.postHelpNotification(HelpNotificationRequest(0))
viewModel.helpNotification.observe(viewLifecycleOwner) {
it?.onLoading {}
it?.onSuccess { result->
result?.let {
InfoDialogWithOneText(
InfoDialogType.GOT_HELP_ASKING_FROM_STAFF
).show(childFragmentManager, InfoDialog.TAG)
}
}
it?.onError { error ->
InfoDialogWithOneText(
InfoDialogType.GOT_HELP_ASKING_FROM_STAFF
).show(childFragmentManager, InfoDialog.TAG)
}
}
}
  • 尝试使用sharedViewModel,但我将不得不为所有人编写观察方法。
  • 尝试baseViewModel,但它得到错误柄视图模型,也会像共享视图模型一样。

对于抽象部分,您希望它需要涵盖所有内容-从提供可观察事件的视图模型到处理它。我不得不更改一些类型,因为您没有提供它们,但将此应用于您的情况应该不会太困难。

abstract class HelpNotificationFragment : Fragment() {
internal abstract val viewModel: HelpNotificationViewModel
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.helpNotification.observe(viewLifecycleOwner) { result ->
println(result)
}
}
}
abstract class HelpNotificationViewModel : ViewModel() {
private val _helpNotification = SingleLiveEvent<Result<Any>>()
// Specify the immutable type otherwise you would expose it as mutable
val helpNotification: LiveData<Result<Any>>
get() = _helpNotification
fun postHelpNotification(helpNotificationRequest: Result<Any>) {
viewModelScope.launch(Dispatchers.IO) {
_helpNotification.postValue(helpNotificationRequest)
}
}
}

这就是你将如何实现使用它的片段-重写视图模型将强制你使用具有适当父视图模型:

@HiltViewModel
class MainViewModel @Inject constructor(): HelpNotificationViewModel()
@AndroidEntryPoint
class MainFragment : HelpNotificationFragment() {
override val viewModel: MainViewModel by viewModels()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_main, container, false)
view.findViewById<Button>(R.id.button).setOnClickListener {
viewModel.postHelpNotification(Result.success("Yay!"))
}
return view
}
}