A better Composable for Jetpack Compose
ChameleonUi is a composable which allows you to define a viewModel for it, so that you have to worry less about the UiState and can freely send events to ViewModels
@Composable
fun <Event : ChameleonEvent, State : ChameleonState> ChameleonUi(
chameleon: Chameleon<Event, State>, // takes in a chameleon of type Event and State
content: @Composable Chameleon<Event, State>.(State) -> Unit,
) {
val uiState by chameleon.uiState.collectAsState()
with(chameleon) {
content(uiState)
}
}
interface ChameleonState
interface ChameleonEvent
open class Chameleon<Event : ChameleonEvent, State : ChameleonState>(
createInitialState: () -> State,
) : ViewModel() {
private val initialState: State by lazy { createInitialState() }
private val currentState: State
get() = uiState.value
private val _uiState: MutableStateFlow<State> = MutableStateFlow(initialState)
val uiState = _uiState.asStateFlow()
private val _event: MutableSharedFlow<Event> = MutableSharedFlow()
val event = _event.asSharedFlow()
fun sendEvent(event: Event) {
val newEvent = event
viewModelScope.launch { _event.emit(newEvent) }
}
fun setState(reduce: State.() -> State) {
val newState = currentState.reduce()
_uiState.value = newState
}
}
@Composable
fun Greeting(
modifier: Modifier = Modifier,
chameleon: ChangingColorChameleon, // This is a typical viewmodel
) {
ChameleonUi(
chameleon = chameleon,
) { state -> // you get the state from a chameleon
Scaffold(modifier) {
Box(
Modifier.fillMaxSize()
.padding(it)
.background(state.color ?: Color.Green),
) {
TextButton(onClick = {
sendEvent(ChangeColorEvent.ClickPerformed) // you can magically send event to the chamelon instance associated to it via kotlin scopes.
}, modifier = Modifier.align(Alignment.Center)) {
Text("Change Color")
}
}
}
}
}
Screen_recording_20231007_005304.mp4
MIT License
Copyright (c) 2023 Anmol Verma
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.