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

[ISSUE-011] BaseViewModel 및 샘플 데이터 생성 #27

Merged
merged 6 commits into from
Jun 3, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions presentation/src/main/java/com/yapp/growth/base/BaseViewModel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.yapp.growth.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

abstract class BaseViewModel<S : ViewState, A : ViewSideEffect, E : ViewEvent>(
initialState: S
) : ViewModel() {

abstract fun handleEvents(event: E)

private val _viewState: MutableStateFlow<S> = MutableStateFlow<S>(initialState)
val viewState = _viewState.asStateFlow()

private val currentState: S
get() = _viewState.value

private val _effect: Channel<A> = Channel()
val effect = _effect.receiveAsFlow()
Comment on lines +21 to +22

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SharedFlow 대신 Channel을 사용한 장점이 있나요?

Copy link
Member Author

@hoyahozz hoyahozz Jun 2, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

effect 의 경우 어떤 이벤트가 발생했을 때 한번만 실행되어야 하는데, 모든 구독자에게 데이터를 방출하는 SharedFlow를 사용하는 것은 옳지 않다고 생각합니다. 반면 Channel 의 경우 한 구독자에게 한번씩만 데이터를 방출하기 때문에, 사용하기 적절하다고 판단했습니다.

SharedFlow 의 경우 구독자가 나타나지 않아도 데이터가 방출되는 반면, Channel 의 경우 구독자가 없을 경우 방출되지 않는데 이 요소 또한 중요하다고 생각합니다.

이 두 이유를 근거로 제가 생각한 하나의 예시를 들어보겠습니다.

버튼을 여러번 눌렀을 때 나타나야 하는 이펙트들을 Channel 로 관리하여 버퍼에서 하나씩 순차적으로 실행되게 설정하고, 실행하는 도중 사용자가 액티비티를 나가면 구독자가 사라지게 되어 Channel 에 쌓인 버퍼도 삭제된다.

라고 판단했는데, 부족한 점이나 틀린 점 지적해주시면 감사하겠습니다 🤣


private val _event: MutableSharedFlow<E> = MutableSharedFlow()

init {
subscribeToEvents()
}

private fun subscribeToEvents() {
viewModelScope.launch {
_event.collect {
handleEvents(it)
}
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

setEvent 에서 바로 handleEvents(event) 를 호출해도 되지 않나요?

한번 더 구독해서 스트림으로 만든 이유가 궁금합니다.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

헉.. 맞네요.. 그 방법이 더 좋은 것 같아요..!
단순히 가독성 향상을 위해 함수를 구성했었던 것 같은데, 그렇다고 굳이 한번 더 구독할 이유는 없었네요..


protected fun setState(reducer: S.() -> S) {
val newState = currentState.reducer()
_viewState.value = newState
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 개념도 setXXX 보다는 updateXXX에 가까운 것 같습니다.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

StateFlow 는 초기값을 줄 수 있으니 그 과정에서 set 은 이미 일어났고, 이 후에 상태 데이터를 보내는 것은 update 의 개념이니 그게 맞는 것 같네욥.... 많이 배워갑니다 ㅠㅠ


protected fun setEffect(builder: () -> A) {
val effectValue = builder()
viewModelScope.launch { _effect.send(effectValue) }
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이펙트를 새로 set 하는 개념이 아닌 emit 하는 개념이라서 setXXX 보다는 그대로 사용하면 어떨까요?

effect { ... }

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

확실히 set 하는 개념은 아니고 effect 라고 쓰기엔 너무 휑해보이는 느낌이 있으니..

sendEffect { ... }

로 고치는 것도 괜찮아보이네욥!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

effect가 빌더 형태의 패턴을 받는 장점이 있을까요.
아무런 파라미터나 리시버가 없으면 단순히 Effect를 파라미터로 받는게 맞지 않을까?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

맞습니다... 다만 setState 도 고차함수를 파라미터로 받다보니 setEffect 도 함께 고차함수를 파라미터로 받고 싶었습니다..


open fun setEvent(event : E) {
viewModelScope.launch { _event.emit(event) }
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

open으로 만든 이유가 있을까요?
자식에서 재정의 하면 의도와 달리 버그가 발생할 수 있지 않을까요

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

맞습니다. 재정의 방지를 위해 open 키워드는 지우도록 하겠습니다..!

}
4 changes: 4 additions & 0 deletions presentation/src/main/java/com/yapp/growth/base/ViewEvent.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.yapp.growth.base

interface ViewEvent {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.yapp.growth.base

interface ViewSideEffect {
}
4 changes: 4 additions & 0 deletions presentation/src/main/java/com/yapp/growth/base/ViewState.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.yapp.growth.base

interface ViewState {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.yapp.growth.ui.sample

import com.yapp.growth.base.ViewEvent
import com.yapp.growth.base.ViewSideEffect
import com.yapp.growth.base.ViewState

class SampleContract {

data class SampleViewState(
Copy link
Member

@jihee-dev jihee-dev May 28, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저희 View, State, Event, Effect의 네이밍을 어떻게 가져갈 것인지 정해야 할 것 같은데
예를 들어 Login 화면이라고 한다면
LoginScreen(파일명), LoginContract, LoginViewState, LoginEvent, LoginSideEffect <- 이렇게 가져가는 건가용?
추가) LoginViewModel

Copy link
Member Author

@hoyahozz hoyahozz May 28, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 베이스 짜면서 이렇게 생각했어요!
LoginScreen
LoginContract
LoginViewState
LoginViewEvent
LoginViewSideEffect
LoginViewModel
앞에 View 를 붙이는게 너무 길다 싶으면 없애도 될 것 같기두 하네용!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아하 올려주신 Sample 보고 옮겨 적은 거였는데,, 제가 잘못 옮겨적었네요..
음 하다 보면 이벤트 이런 것들의 이름이 조금 길어지는 경우가 많았던 것 같아서 저는 View를 제외해도 좋을 것 같습니다!
(사실 큰 상관은 없어용,,ㅎㅎ..)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋아요! 그럼 다른건 그대로 유지하되
Event, SideEffect 의 경우엔 View를 빼고 작명하면 될 것 같아요!
LoginEvent
LoginSideEffect

val isLoading: Boolean = false
) : ViewState

sealed class SampleViewSideEffect : ViewSideEffect {
object NavigateToAnyScreen : SampleViewSideEffect()
data class ShowToast(val msg: String) : SampleViewSideEffect()
}

sealed class SampleViewEvent : ViewEvent {
object OnAnyButtonClicked : SampleViewEvent()
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.yapp.growth.ui.sample

import com.yapp.growth.base.BaseViewModel
import com.yapp.growth.domain.usecase.UseCase
import com.yapp.growth.ui.sample.SampleContract.*

class SampleViewModel(
private val useCase: UseCase
) : BaseViewModel<SampleViewState, SampleViewSideEffect, SampleViewEvent>(
SampleViewState()
) {

fun anyFunction() {
// anything do . . .
setEffect { SampleViewSideEffect.NavigateToAnyScreen }
setState { copy(isLoading = false) }
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

anyFuction()은 private이 되어야 할 것 같네요

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 현재 코드에선 맞습니다 ㅠ!


override fun handleEvents(event: SampleViewEvent) {
when (event) {
is SampleViewEvent.OnAnyButtonClicked -> {
setState { copy(isLoading = true) }
anyFunction()
}
}
}
}