Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Kotlin Flow] Using "launchIn" instead of "collect" for collecting Flows in ViewModel #425

Closed
luongvo opened this issue Mar 7, 2023 · 0 comments · Fixed by #441
Closed

Comments

@luongvo
Copy link
Member

luongvo commented Mar 7, 2023

Why

Using launchIn instead of collect for collecting Flows in ViewModel is recommended way, because:

  • collect() will block the coroutine until the flow has finished emitting. This behavior is sometimes desired, but it’s not in most cases.
  • launchIn is less code to write, we don’t have to have indentations, and easier to understand.
  • We can eliminate the execute operator in the BaseVIewModel.

Sample implementation:

        logInUseCase(
            email = email,
            password = password
        )
            .onStart { showLoading() }
            .onCompletion { hideLoading() }
            .catch { e -> _error.emit(e) }
            .onEach {
                _isLoggedIn.emit(true)
                navigateToHome()
            }
            .launchIn(viewModelScope)

RFC discussion: #408

References:

Who Benefits?

Developers

@luongvo luongvo self-assigned this Mar 7, 2023
@ryan-conway ryan-conway added this to the 3.18.0 milestone Mar 8, 2023
luongvo added a commit that referenced this issue Mar 15, 2023
luongvo added a commit that referenced this issue Mar 27, 2023
@ryan-conway ryan-conway modified the milestones: 3.18.0, 3.19.0 Apr 3, 2023
ryan-conway added a commit that referenced this issue Apr 10, 2023
…d-of-collect

[#425] [Kotlin Flow] Using "launchIn" instead of "collect" for collecting Flows in ViewModel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants