Skip to content

Instantly share code, notes, and snippets.

@tfcporciuncula
Last active September 16, 2024 19:07
Show Gist options
  • Save tfcporciuncula/881465322f0cbe7b6974b508cc2e3a58 to your computer and use it in GitHub Desktop.
Save tfcporciuncula/881465322f0cbe7b6974b508cc2e3a58 to your computer and use it in GitHub Desktop.
DelegationDemo
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import de.zalando.lounge.compose.lux.Surface
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject
import kotlin.random.Random
class DemoUseCase {
operator fun invoke(): Flow<List<Int>> {
return flow {
while (true) {
emit(List(10) { Random.nextInt(0, 100) })
delay(1000)
}
}
}
}
class DemoDelegate @Inject constructor(
private val useCase: DemoUseCase,
) {
operator fun invoke(): Flow<List<LoungeButtonState>> {
return useCase().map {
it.map {
LoungeButtonState(
text = "Random number $it",
onClick = {
doSomething(it)
},
)
}
}
}
private fun doSomething(randomNumber: Int) {
// do something with the number
}
}
data class DemoState(
val buttonStates: List<LoungeButtonState> = emptyList(),
)
class DemoViewModel @Inject constructor(
delegate: DemoDelegate,
) : ViewModel() {
private val _viewState = MutableStateFlow(DemoState())
val uiState: StateFlow<DemoState> = _viewState
val state = DemoState(emptyList())
init {
delegate().onEach { buttonStates ->
_viewState.value = state.copy(
buttonStates = buttonStates,
)
}.launchIn(viewModelScope)
}
}
// please imagine a fragment.
@Composable
fun DemoScreen(
viewModel: DemoViewModel,
) {
val uiState by viewModel.uiState.collectAsState()
DemoScreen(uiState)
}
@Composable
fun DemoScreen(state: DemoState) {
Surface {
Column {
state.buttonStates.forEach { buttonState ->
LoungeButton(buttonState)
}
}
}
}
data class LoungeButtonState(
val text: String,
val onClick: () -> Unit,
)
@Composable
fun LoungeButton(state: LoungeButtonState) {
// render
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment