You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在多个Fragment中复用同一ViewModel的方法与观察逻辑?

解决方案:通过Fragment扩展复用SharedViewModel观察逻辑

你可以通过创建Fragment扩展函数封装SharedViewModel中helpNotification的观察逻辑,实现一次编写、多处复用。以下是具体实现步骤:

1. 确保Hilt配置正确

首先确认宿主Activity已添加@AndroidEntryPoint注解,所有需要使用该扩展的Fragment也需添加该注解,保证Hilt能正确注入SharedViewModel:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() { ... }

@AndroidEntryPoint
class YourFragment : Fragment() { ... }

2. 创建Fragment扩展函数

新建FragmentExtensions.kt文件,编写扩展函数封装观察逻辑:

import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.yourpackage.SharedViewModel
import com.yourpackage.InfoDialogWithOneText
import com.yourpackage.InfoDialogType
import com.yourpackage.InfoDialog

// 基础版本:固定逻辑复用
fun Fragment.setupHelpNotificationObserver() {
    val viewModel: SharedViewModel by activityViewModels()
    
    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)
        }
    }
}

// 进阶版本:支持自定义回调(可选)
fun Fragment.setupHelpNotificationObserver(
    onLoading: () -> Unit = {},
    onSuccess: (BaseResponse<Any>?) -> Unit = { result ->
        result?.let {
            InfoDialogWithOneText(InfoDialogType.GOT_HELP_ASKING_FROM_STAFF)
                .show(childFragmentManager, InfoDialog.TAG)
        }
    },
    onError: (String?) -> Unit = {
        InfoDialogWithOneText(InfoDialogType.GOT_HELP_ASKING_FROM_STAFF)
            .show(childFragmentManager, InfoDialog.TAG)
    }
) {
    val viewModel: SharedViewModel by activityViewModels()
    
    viewModel.helpNotification.observe(viewLifecycleOwner) {
        it?.onLoading(onLoading)
        it?.onSuccess(onSuccess)
        it?.onError(onError)
    }
}

3. 在Fragment中复用逻辑

在需要观察helpNotification的Fragment中,只需调用扩展函数即可:

@AndroidEntryPoint
class MainFragment : Fragment() {
    private val viewModel: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 初始化观察逻辑
        setupHelpNotificationObserver()
        
        // 触发请求(示例)
        viewModel.postHelpNotification(HelpNotificationRequest(0))
    }
}

如果需要自定义某个Fragment的处理逻辑,使用进阶版本的扩展:

setupHelpNotificationObserver(
    onSuccess = { result ->
        // 自定义成功逻辑
        Toast.makeText(context, "请求成功", Toast.LENGTH_SHORT).show()
    },
    onError = { errorMsg ->
        // 自定义错误逻辑
        Log.e("HelpNotification", "错误:$errorMsg")
    }
)

关键说明

  • 使用activityViewModels()确保获取的是与宿主Activity共享的SharedViewModel实例。
  • 扩展函数中使用viewLifecycleOwner绑定Fragment生命周期,避免内存泄漏。
  • 进阶版本通过默认参数保留原有逻辑,同时支持按需自定义。

内容的提问来源于stack exchange,提问作者Ahmet Yılmaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 10:45:47