xxfast
01/06/2022, 4:36 AMFlow<State>
from a shared ViewModel
, in a Typescript react app (not using kotlin react wrappers). This is how that looks like
// View.tsx
export function View() {
const viewModel = new JsViewModel()
const [state, setState] = useState(viewModel.initialState)
useEffect(() => {
viewModel.subscribe((state) => { setState(state) })
})
return (
<p>{state.value}</p>
)
}
// ViewModel.kt
@JsExport
class JsViewModel {
...
private val viewModel: ViewModel by viewModel()
fun subscribe(
onChange: (state: State) -> Unit,
) {
viewModel.launch {
viewModel.states.collect { state -> onChange(state) }
}
}
}
This pretty much works, but there’s a collect
launched, which is technically not managed. Is there a better way to hookup the kotlin flow with the react hook?Lukasz Kalnik
01/10/2022, 12:43 PMLukasz Kalnik
01/10/2022, 12:44 PMcollect
through the lifetime of your application you can leave it unmanaged. However if you want to collect different things on different screens, you definitely need a mechanism to cancel.xxfast
01/17/2022, 11:56 PMxxfast
01/17/2022, 11:58 PMcomponentWillUnmount
/ useEffect.cleanup
hook. Thats the only way i found out so far.