Is there an example of how to write custom hooks i...
# compose
o
Is there an example of how to write custom hooks in Compose? In React, you can extract logic into a hook. No UI, just pure logic. Curious how people would do this in Compose
n
What kind of logic? I/O or other side effects, or just control flow?
o
something like const [isUploading, uploadMessage] = useUploadMessage()
Something that accepts events and emits data
a
Flow<T>.collectAsState
,
produceState
, and
LaunchedEffect
will all likely be interesting to you
k
Well, not a hooks per se, but you could achieve something similar by using Effects and State. For example:
Copy code
private class MyLogic(val scope: CoroutineScope, val otherNoneCompose: String){/* implement some business logic */}

@Composable
fun MyHook(dependencies: String) {
  val scope = rememberCoroutineScope()
  val myLogic = remember(scope, dependencies) { MyLogicHere(scope, dependencies) }

  DisposableEffect(dependencies) {
    onDispose {}
  }

  return myLogic
}
👍 1
c
or you could just use LaunchedEffect instead of DisposableEffect and run myLogic as a suspend lambda inside
👍 1