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
nschulzke
04/12/2022, 3:13 PM
What kind of logic? I/O or other side effects, or just control flow?
o
Orhan Tozan
04/12/2022, 3:15 PM
something like
const [isUploading, uploadMessage] = useUploadMessage()
Orhan Tozan
04/12/2022, 3:15 PM
Something that accepts events and emits data
a
Adam Powell
04/12/2022, 3:41 PM
Flow<T>.collectAsState
,
produceState
, and
LaunchedEffect
will all likely be interesting to you
k
krzysztof
04/12/2022, 3:42 PM
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
Csaba Szugyiczki
04/13/2022, 7:00 AM
or you could just use LaunchedEffect instead of DisposableEffect and run myLogic as a suspend lambda inside