【问题标题】:Fragment.viewLifecycleOwnerLiveData.observe doesn't call with kodeinFragment.viewLifecycleOwnerLiveData.observe 不使用 kodein 调用
【发布时间】:2021-02-11 16:04:39
【问题描述】:

我正在制作一个应用程序,我想将我的 UI 逻辑分成多个 UI 类,其中 BaseUi 类可以感知生命周期。我使用 Kodein 作为我的 DI,当我的 ui 类的实例被 Kodein 检索时,我遇到了 fragment.viewLifecycleOwnerLiveData.observe 没有被调用的问题。 这是我的片段类:

class ListFragment : Fragment(), DIAware {

    override val di: DI by closestDI()
    override val diTrigger: DITrigger = DITrigger()

    private var binding: FragmentMoviesBinding? = null

    private val fragmentBinding get() = binding

    private val kodeinMoviesUi: MoviesUi by instance() //fragment does not observe viewLifecycleOwnerLiveData

    private val moviesUi: MoviesUi = MoviesUi(this) //fragment now observe viewLifecycleOwnerLiveData

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentMoviesBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        diTrigger.trigger()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }
}

BaseUi 类:

abstract class BaseUi<F : Fragment>(private val fragment: F) : LifecycleObserver {

    init {
        fragment.viewLifecycleOwnerLiveData.observe(fragment, { subscribeToLifecycle() })
    }

    private fun subscribeToLifecycle() {
        fragment.viewLifecycleOwner.lifecycle.addObserver(object : LifecycleObserver {
            @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
            fun onCreate() {
                onViewCreated()
            }
        })
    }

    abstract fun onViewCreated()
}

还有 UIModule:

val uiModule = DI.Module("uiModule") {
    bind<ListFragment>() with provider { ListFragment() }
    bind<MoviesUi>() with provider { MoviesUi(instance()) }
}

【问题讨论】:

  • 片段不应由 DI 框架创建,除非您还使用自定义 FragmentFactory。
  • 还可以查看这篇文章,因为您在生命周期观察逻辑中继承了一个错误:itnext.io/…

标签: android android-livedata android-architecture-components kodein


【解决方案1】:

来自https://github.com/Kodein-Framework/Kodein-DI/issues/353的交叉帖子

这是你的问题bind&lt;ListFragment&gt;() with provider { ListFragment() }

您将ListFragment 与提供者绑定,这意味着每次您向容器请求时,它都会创建ListFragment 的实例。所以,当你用private val kodeinMoviesUi: MoviesUi by instance() 注入MoviesUi 时,它会得到另一个ListFragment 实例。

我建议您将MoviesUi 的绑定定义为工厂,等待接收ListFragment 实例: bind&lt;MoviesUi&gt;() with factory {fragment: ListFragment -&gt; MoviesUi(fragment) } 然后您可以将其注入ListFragment,例如: private val kodeinMoviesUi: MoviesUi by instance(args = this)

【讨论】:

    猜你喜欢
    • 2016-11-29
    • 2019-08-16
    • 2022-01-03
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    相关资源
    最近更新 更多