I'm using a Flow
just to communicate from the ViewModel with an activity, but I dont really need to pass any parameter to the activity. I just need the activity to react to the call.
Right now I have a flow of a nullable type:
val myFlow: Flow<Nothing?> = someChannel.receiveAsFlow()
And I need to emit a null, since Nothing
cannot be instantiated:
someChannel.send(null)
What I'd like to do:
val myFlow: Flow<Nothing>
and then:
someChannel.send()
But of course that doesn't compile.
Is there a better way of doing this?
CodePudding user response:
Like mentioned in another answer, Nothing
has a different purpose. You can also consider using Unit
for that:
val myFlow: Flow<Unit> = someChannel.receiveAsFlow()
someChannel.send(Unit)
If you have a couple of places in the code where you call someChannel.send(Unit)
you can create an extension function on SendChannel
and call it instead of someChannel.send(Unit)
:
suspend fun SendChannel<Unit>.send() = send(Unit)
And then just call:
someChannel.send()
CodePudding user response:
Nothing
is intended for a different purpose.
From the kotlin docs:
Nothing has no instances. You can use Nothing to represent "a value that never exists": for example, if a function has the return type of Nothing, it means that it never returns (always throws an exception).
But you try to emit a null
value (it isn't Nothing
). So, it looks like you are looking for a workaround where you really don't need it.
You can just create for example an EmptyState
type and use it
val myFlow: Flow<EmptyState>