3

I have thought that is okay to collect SharedFlow data on onViewCreated. But when i replace fragment n times then fire some event to SharedFlow, it emits n times event to me instead of one event.

I have fixed it how i put my code on onCreate at my Fragment. But i haven't found any documentation about that. Am i missing something or i should keep using SharedFlow collections at onCreate in Fragment ?

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    lifecycleScope.launchWhenResumed {
        viewModel.uiEffect.collect {
            when (it) {
                is ViewEffectWrapper.PageEffect -> {
                    if (it.pageEvent is LoginViewEffect.OpenHomePage) {
                        startActivity(
                            Intent(
                                this@LoginFragment.context,
                                HomeActivity::class.java
                            )
                        )
                    }
                }

            }
        }
    }
}

And here is my SharedFlow definition at ViewModel

private val _uiEffect = MutableSharedFlow<ViewEffectWrapper<LoginViewEffect>>(replay = 0)
val uiEffect: SharedFlow<ViewEffectWrapper<LoginViewEffect>> = _uiEffect
Gökberk Yağcı
  • 376
  • 1
  • 4
  • 10

1 Answers1

14

You are not currently using the viewLifecycleOwner and it is recommended to use that for Fragments as that is tied to the Fragment Views Lifecycle. This is the recommended way to do it

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        // ...
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.uiEffect.collect {
                    // do stuff here
                }
            }
        }
    }

I would also like to give this a read. It is a good read and worth to help you ahead.

https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda

che10
  • 2,176
  • 2
  • 4
  • 11