Where can I find that one to use with Compose for ...
# compose-desktop
x
Where can I find that one to use with Compose for Desktop
z
It doesn't exist. ViewModel, like most androidx libraries, is only available for Android.
x
Ok but how to do the undirectional state management then?
I read the JetPack Compose Guide but it kinda only is valid for Android (like the stuff with ViewModel)
Isn't there a real guide for the "for Desktop" stuff?
z
I don't think there's an official guide for desktop yet, desktop support is pretty new and still very experimental afaik.
Unidirectional data flow doesn't require VM - it's just a pattern, and there are many ways to implement it
👆 4
You might want to take a look at Decompose
🔥 2
x
z
Yep
x
^^
i
Unidirectional data flow doesn't require VM
ViewModel also can be considered as a pattern (Model - ViewModel - View). We can use something like this:
Copy code
@Composable
fun HomeView() {
    val viewModel = remember { HomeViewModel() }
    Text("Count ${viewModel.counter}")
}

class HomeViewModel {
  var counter by mutableStateOf(3)
}
or
Copy code
@Composable
fun HomeView() {
    val viewModel = remember { HomeViewModel() }
    Text("Count ${viewModel.counter.collectAsState().value}")
}

class HomeViewModel {
  var counter = StateFlow(3)
}
c
Here's what I'm doing, if you would like a coroutine scope for your ViewModel:
Copy code
abstract class ViewModel(di: DI) : DIAware by di {
    private val job = Job()
    protected val lifecycleScope: CoroutineScope = CoroutineScope(job)

    fun dispose() {
        job.complete()
    }
}

@Composable
inline fun <reified T : ViewModel> viewModel(): T {
    val di = AmbientDI.current
    val viewModel = remember { T::class.java.constructors.single().newInstance(di) as T }
    DisposableEffect(viewModel) {
        onDispose {
            viewModel.dispose()
        }
    }
    return viewModel
}
This wouldn't be too hard to remove the reflection or DI if you'd rather not use those.
x
@Cedrick Cooke thanks to you I feel like an amateur developer since I am not able to understand your code at all 😵
but do not bother explaining it to me - I am using the way to just pass down mutableState and it works fine for me
g
I don't see why do you need Androidx ViewModel, the only why it needed is to support configuration change on Android, which really is not an issue on desktop (and also not needed for compose-only apps) Just create any own class/interface with Flow properties Sharing code between Android and Desktop is the only good reason, but also possible to achieve without exposing VM
☝️ 1