Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/numq/viewmodel

ViewModel implementation
https://github.com/numq/viewmodel

architecture-component compose compose-desktop desktop jetpack kmm kmm-mvvm kotlin kotlin-compose kotlin-desktop kotlin-library kotlin-multiplatform multiplayer mvvm state-machine state-management viewmodel vm

Last synced: 21 days ago
JSON representation

ViewModel implementation

Awesome Lists containing this project

README

        

## ViewModel

ViewModel implementation focused on applying the *MVVM* architectural pattern and the *State Reduction* approach in
developing a *Kotlin Jetpack Compose Desktop* application

### Components

- CloseableCoroutineScope
- ViewModel
- StateViewModel

### Dependencies

```
val coroutinesVersion = "1.6.4"
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion")
```

### Usage examples

- [Stash Android](https://github.com/numq/stash)
- [Stash Desktop](https://github.com/numq/stash-desktop)

### Koin injection

```kotlin
val auth = module {
factory { GetUserId(get()) }
single { AuthViewModel(get()) }
}
```

### State managing

Use case example implementation:

```kotlin
class GetUserId constructor(
coroutineScope: CoroutineScope,
arg: Unit,
onException: (Exception) -> Unit,
onResult: (T) -> Unit = {}
) : UseCase()
```

Sealed class as state:

```kotlin
sealed class AuthState private constructor() {
object Unauthenticated : AuthState()
object Authenticating : AuthState()
data class Authenticated(val userId: String? = null) : AuthState()
}

class AuthViewModel constructor(
private val getUserId: GetUserId
) : StateViewModel(AuthState.Unauthenticated) {
fun authenticate() = getUserId.invoke(viewModelScope, Unit, onException) { flow ->
updateState { AuthState.Authenticating }
viewModelScope.launch {
flow.collect { id ->
updateState {
id?.let { AuthState.Authenticated(id) } ?: AuthState.Unauthenticated
}
}
}
}
}
```

Data class as state:

```kotlin
data class AuthState(val userId: String? = null)

class AuthViewModel constructor(
private val getUserId: (CoroutineScope, Unit, (Exception) -> Unit, (Flow) -> Unit) -> Unit
) : StateViewModel(AuthState()) {
fun authenticate() = getUserId.invoke(viewModelScope, Unit, onException) { flow ->
viewModelScope.launch {
flow.collect { id ->
updateState {
it.copy(userId = id)
}
}
}
}
}
```