Daniele B
03/12/2021, 6:12 PMdata class AppState (
val masterState : MasterState = MasterState(),
)
data class MasterState (
val isLoading : Boolean = false,
)
is there a more concise way than this?
val myState = AppState()
val newState = myState.copy(masterState = myState.masterState.copy(isLoading = true))
ephemient
03/12/2021, 8:44 PMDaniele B
03/12/2021, 10:11 PMupdateSubstate
, where I could perform the substate copy inside the block, and the root state copy inside the function:
// this is the specific function
fun MyModel.anExtensionFunction() {
updateSubstate {
it.masterState.copy(isLoading = true)
}
}
but I don’t know how to deal with the reflection:
class MyModel {
var myState = AppState()
// this is the generic function
fun updateSubstate(block: (AppState) -> Any) {
val output = block(myState)
...
myState = myState.copy(PROPERTY_NAME_TO_GET_FROM_BLOCK_BETWEEN_IT_AND_COPY = output)
}
}
ephemient
03/12/2021, 10:32 PMval copyFunction = AppState::copy
val thisParameter = copyFunction.parameters.find { it.kind == INSTANCE }!!
val propertyParameter = copyFunction.parameters.find { it.name == parameterName }!!
myState = copyFunction.callBy(mapOf(thisParameter to myState, propertyParameter to output))
but (as all things reflection) there is no safety here. do you really need to do this?Daniele B
03/12/2021, 10:34 PMDaniele B
03/12/2021, 10:42 PMDaniele B
03/12/2021, 11:13 PMDaniele B
03/12/2021, 11:14 PMupdateMasterState {
it.copy(isLoading = true)
}
even if I have to create a function for each substate:
fun updateMasterState(block: (MasterState) -> MasterState) {
myState = myState.copy(masterState = block(myState.masterState))
}