I'm using a custom made State class to store resul...
# coroutines
f
I'm using a custom made State class to store result but seems compiler is complaining about the different types Does anyone know any workaround for this? Code in 🧵
Copy code
sealed interface UiState<out T> {
    data class Success<T>(val value: T) : UiState<T>
    data class Error(val exception: Throwable? = null, val message: String = ""): UiState<Nothing>
    data object Loading : UiState<Nothing>
}
Copy code
val currentPathFiles: StateFlow<UiState<List<File>>> = currentPath
        .filterNotNull()
        .flowOn(<http://dispatcher.io|dispatcher.io>())
        .flatMapLatest { directoryProvider.observeDir(it) }
        .map { UiState.Success(it) }
        .catch { emit(UiState.Error(it)) }
        .toStateFlow(initialState = UiState.Loading)
d
Try
Copy code
.map { UiState.Success(it) as UiState<List<File>> }
Otherwise,
map
thinks that the new flow type must be
UiState.Success
, as that's the most specific type it can infer. You can let it know that you want a less specific type.
gratitude thank you 1
f
@Dmitry Khalanskiy [JB] it works, but IDE thinks it's a useless cast 🫠
c
it
in
catch
is a exception so you are not emitting a UIState with list as declared in the return type
r
you can also specify the generic type at that map call to make it clear you want UIState and not UIState.Success, otherwise it will infer the most specific type at that point which is Success
e
btw you can do either of
Copy code
.map<_, UiState<List<File>>> { UiState.Success(it) }
.catch { emit(UiState.Error(it)) }
or
Copy code
.map { UiState.Success(it) }
.catch<UiState<List<File>>> { UiState.Error(it) }
which avoids
as