Reputation: 3265
I have a sealed interface for my UIState.
sealed interface UIState<out T> {
object ShowLoading : UIState<Nothing>
object ShowEmptyData : UIState<Nothing>
data class ShowData<out T>(val data: T) : UIState<T>
data class ShowError(val errorUIState: ErrorUIState) : UIState<Nothing>
}
This is general for most of the screens in my application, but let's take I have a search screen and along with this states I need one more state
object ShowNoSearchResult: UIState<Nothing>
If I add this state inside UIState
sealed interface, in all the screens I need to handle this state, but I need it only in the search screen.
As a solution, I tried to create a new sealed interface and extend the UIState.
sealed interface SearchUIState<out T>: UIState<T> {
object ShowNoSearchResult: SearchUIState<Nothing>
}
Now the issue is that I can't call any UIState
class using my SearchUIState
. The ShowLoading
, ShowEmptyData
, etc. are not available if I use SearchUIState
.
What I want is to use SearchUIState
to handle all the states of the SearchUIState
and its parent states as well? Is there a way to do this without code duplication?
P.S. Actually using the parent sealed interface I can return the child sealed interface state as well. The thing is that still when I handle parent sealed interface states using when
, it requires to handle also all the child sealed interface states.
Upvotes: 5
Views: 1598
Reputation: 93834
You can make each of the UIState children also implement SearchUIState, and you can change SearchUIState to not be a subtype of UIState.
sealed interface UIState<out T> {
object ShowLoading : UIState<Nothing>, SearchUIState<Nothing>
object ShowEmptyData : UIState<Nothing>, SearchUIState<Nothing>
data class ShowData<out T>(val data: T) : UIState<T>, SearchUIState<T>
data class ShowError(val errorUIState: ErrorUIState) : UIState<Nothing>, SearchUIState<Nothing>
}
sealed interface SearchUIState<out T> {
object ShowNoSearchResult: SearchUIState<Nothing>
}
Upvotes: 1