Skip to content

Instantly share code, notes, and snippets.

@DevPicon
Created August 23, 2024 05:00
Show Gist options
  • Save DevPicon/0d2fc4004b50da41babafc7cca21e5f8 to your computer and use it in GitHub Desktop.
Save DevPicon/0d2fc4004b50da41babafc7cca21e5f8 to your computer and use it in GitHub Desktop.
package la.devpicon.android.composenavigationapplication
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
@Composable
fun Stateful(
viewModel: MyViewModel,
modifier: Modifier = Modifier
) {
val state by viewModel.viewState.collectAsState()
Stateless(
state = state,
onClick = viewModel::updateName
)
}
@Composable
fun Stateless(
state: MyState,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
}
class MyViewModel() : BaseViewModel<MyState, MyEvent, MyEffect>() {
override fun getInitialState(): MyState {
return MyState(name = "default")
}
fun updateName() {
TODO("Not yet implemented")
}
}
abstract class BaseViewModel<STATE : UiState, in EVENT : UiEvent, EFFECT : UiEffect> : ViewModel() {
private val _viewState = MutableStateFlow<STATE>(getInitialState())
val viewState = _viewState.asStateFlow()
abstract fun getInitialState(): STATE
}
data class MyState(
val name: String
) : UiState
sealed class MyEvent : UiEvent
sealed class MyEffect : UiEffect
interface UiState
interface UiEvent
interface UiEffect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment