https://kotlinlang.org logo
#compose
Title
# compose
f

Fudge

07/26/2020, 4:33 PM
I wonder, is it possible to do something like this?
Copy code
@Composable suspend fun askQuestion() : Answer {
   return suspendCoroutine { continuation -> 
      QuestionComponent(onAnswer = {answer -> continuation.resume(answer)})
   }
}
The problem is that if I do something like this
Copy code
setContent {
    runBlocking { askQuestion() }
}
It won't compile because "@Composable invocations can only happen from the context of a @Composable function"
a

Adam Powell

07/26/2020, 4:34 PM
Yes, but the shape ends up being something a little different. Composable functions are declarative, they have to be able to answer questions about the state of the UI immediately and synchronously.
Your hoisted state objects can manage their own state based on suspension, however
f

Fudge

07/26/2020, 4:36 PM
Do you have an example?
a

Adam Powell

07/26/2020, 4:36 PM
yep, was just digging it out of my gists from a couple months ago 🙂
specifically, take a look at the
SnackMenu
class - that's the hoisted state object bridging suspending request-response API with compose-aware state
the rest outside of that is basically placeholder
substitute the snackbar data with your question data from your code snippet and you can see how this sort of thing can fit together
f

Fudge

07/26/2020, 4:42 PM
I never understand creating an interface for one implementation
thanks, this is roughly the same thing
👍 1
a

Adam Powell

07/26/2020, 4:44 PM
in this case because kotlin doesn't let you declare the constructor of a concrete class as being private to a containing class, or file-private
outside of a library setting this would matter a lot less
f

Fudge

07/26/2020, 4:46 PM
wouldn't
private constructor
do exactly that?
i.e.
class Snack private constructor(...)
a

Adam Powell

07/26/2020, 4:47 PM
no, the containing class can't construct it if the nested class's constructor is private
only the
Snack
class or its companion object could call it
so then that just moves the visibility games to the companion object and the same problem exists
the public interface/private class thing is a bit repetitive but ends up clearer than those alternatives in most cases
👍 2
l

Leland Richardson [G]

07/26/2020, 7:10 PM
FWIW, in dev16 the code you posted at the top of the thread will fail to compile with a different error message: “Suspend functions cannot be made Composable”
😯 1
right now composable suspend functions are difficult to assign a meaning to, and we don’t compile them in any useful way right now, so they are just disabled completely. We have some ideas on what it might mean in the future, but by preventing them now we unlock the ability to enable them in the future in a non-breaking way once we have a better idea of how a suspend composable function should behave.
8 Views