Hi all!. Not sure if anyone has done this before, ...
# multiplatform
x
Hi all!. Not sure if anyone has done this before, but I’m trying to consume a
Flow<State>
from a shared
ViewModel
, in a Typescript react app (not using kotlin react wrappers). This is how that looks like
Copy code
// 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?
l
I guess if you
collect
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.
x
sorry for the late reply. I’m looking for a solution that doesn’t use wrappers
also, i found out that we can technically do some clean up in
componentWillUnmount
/
useEffect.cleanup
hook. Thats the only way i found out so far.