https://kotlinlang.org logo
Title
x

xetra11

11/25/2020, 2:10 PM
Where can I find that one to use with Compose for Desktop
z

Zach Klippenstein (he/him) [MOD]

11/25/2020, 2:15 PM
It doesn't exist. ViewModel, like most androidx libraries, is only available for Android.
x

xetra11

11/25/2020, 2:16 PM
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

Zach Klippenstein (he/him) [MOD]

11/25/2020, 2:23 PM
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

xetra11

11/25/2020, 2:24 PM
z

Zach Klippenstein (he/him) [MOD]

11/25/2020, 2:24 PM
Yep
x

xetra11

11/25/2020, 2:25 PM
^^
i

Igor Demin

11/25/2020, 4:00 PM
Unidirectional data flow doesn't require VM
ViewModel also can be considered as a pattern (Model - ViewModel - View). We can use something like this:
@Composable
fun HomeView() {
    val viewModel = remember { HomeViewModel() }
    Text("Count ${viewModel.counter}")
}

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

class HomeViewModel {
  var counter = StateFlow(3)
}
c

Cedrick Cooke

11/25/2020, 7:49 PM
Here's what I'm doing, if you would like a coroutine scope for your ViewModel:
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

xetra11

11/25/2020, 10:15 PM
@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

gildor

11/26/2020, 3:14 PM
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