, where I could perform the substate copy inside the block, and the root state copy inside the function:
Copy code
// 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:
Copy code
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)
}
}
e
ephemient
03/12/2021, 10:32 PM
Copy code
val 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?
d
Daniele B
03/12/2021, 10:34 PM
thanks!
does this just work on JVM or on all platforms?
Daniele B
03/12/2021, 10:42 PM
I am running it in CommonMain and the IDE can’t find many properties. Do I need to import Reflect as a dependency too?
Daniele B
03/12/2021, 11:13 PM
I think I found a good solution, even without reflection, cleaner than before:
Daniele B
03/12/2021, 11:14 PM
Copy code
updateMasterState {
it.copy(isLoading = true)
}
even if I have to create a function for each substate: