`viewModel.kt` ```@HiltViewModel class HomeViewMod...
# compose
n
viewModel.kt
Copy code
@HiltViewModel
class HomeViewModel @Inject constructor(...) {

  private val snackBarChanel = Channel<StatusSnackbarType>(Channel.BUFFERED)
  val snackBarFlow = snackBarChanel.receiveAsFlow()

  fun onStatusAction(action: StatusAction, context: Context) {
    val clipManager =
      context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
    viewModelScope.launch {
      when (action) {
        is StatusAction.Favorite -> ...
        is StatusAction.Reblog -> ...
        is StatusAction.Bookmark -> {
          if (action.bookmark) api.bookmarkStatus(action.id) else api.unbookmarkStatus(action.id)
          snackBarChanel.send(StatusSnackbarType.Bookmark)
        }
        is StatusAction.CopyText -> {
          clipManager.setPrimaryClip(ClipData.newPlainText("PLAIN_TEXT_LABEL", action.text))
          snackBarChanel.send(StatusSnackbarType.Text)
        }
        is StatusAction.CopyLink -> {
          clipManager.setPrimaryClip(ClipData.newPlainText("PLAIN_TEXT_LABEL", action.link))
          snackBarChanel.send(StatusSnackbarType.Link)
        }
        is StatusAction.Mute -> Unit // TODO
        is StatusAction.Block -> Unit
        is StatusAction.Report -> Unit
      }
    }
  }
}
MyComposable
Copy code
StatusListItem(
  status = status,
  action = {
    viewModel.onStatusAction(it, context)
  },
  navigateToDetail = {...},
  navigateToMedia = {...},
  navigateToProfile = {...},
  modifier = ...
) 
LaunchedEffect(Unit) {
  viewModel.snackBarFlow.collect {
    snackbarState.showSnackbar(it)
  }
}
I have a question about architecture, such as in the code above, where my
@Composable
is used in multiple places and I also have multiple viewModels using the
onStatusAction
method. Is there a good way for multiple viewModels to easily use
onStatusAction
and
snackbarChannel
? 🤔
x
I would define another small
ViewModel
that contains that comon logic and use two `ViewModel`s for each screen where that logic is needes. There's no rule limiting you from having 2 `ViewModel`s for a Composable screen for cases where it makes sense
v
To make your composable reusable - don't couple it to the Viewmodel. Hoist the action callback to the upper level and let the whoever called the composable to pass the action to the ViewModel.