1

I'm trying to reuse compose function and viewmodel in different place. I can reuse compose function, however, I don't know how to reuse viewmodel. how can I reuse?

@Composable
fun SaveView(saveViewModel: SaveViewModel = hiltViewModel()) {
    ...
}

class SaveViewModel : ViewModel() {
}

I hope to reuse this two in other place.

  1. And I also want to know share this viewmodel in different place.

view - viewmodel A-B

C-B

D-E

Kyu-Ho Hwang
  • 143
  • 11
  • You can create the `ViewModel` in the Activity and pass it along the way to `composable functions` as argument. Thats on only way i know . may be there is another way or maybe not .. – ADM Dec 30 '21 at 04:52
  • 2
    `hiltViewModel` is already gonna return the same object from any composable within a single context, e.g. activity, fragment or a navigation route. If you need to shared it between multiple navigation routes, check out [this answer](https://stackoverflow.com/a/69002254/3585796) – Phil Dukhov Dec 30 '21 at 04:55
  • @Philip Dukhov Thanks for your reply. I know this. I hope to reuse in different place viewmodel and views for different purpose. So, I have to share viewmodel in A group, and I want to make new viewmodel in B group. eg) alert view and view model in A(terms of use) and B(DB commit success) – Kyu-Ho Hwang Dec 30 '21 at 11:02
  • Does this answer your question? [How to create separate ViewModels per list item when using Compose UI?](https://stackoverflow.com/questions/69754308/how-to-create-separate-viewmodels-per-list-item-when-using-compose-ui) – Phil Dukhov Dec 31 '21 at 02:48

0 Answers0