https://kotlinlang.org logo
#coroutines
Title
# coroutines
e

Eric Ampire [MOD]

10/30/2020, 12:56 PM
With LiveData we could easily reach the same logic, so I would like to know the difference between
LiveData
and
StateFlow
.
Copy code
class DownloadingModel {

   private val _state = MutableStateFlow<DownloadStatus>(DownloadStatus.NOT_REQUESTED)
   val state: StateFlow<DownloadStatus> get() = _state

   suspend fun download() {
       _state.value = DownloadStatus.INITIALIZED
       initializeConnection()
       processAvailableContent {
               partialData: ByteArray,
               downloadedBytes: Long,
               totalBytes: Long
           ->
           storePartialData(partialData)
           _state = DownloadProgress(downloadedBytes.toDouble() / totalBytes)
       }
       _state.value = DownloadStatus.SUCCESS
   }
}
🔥 1
👍 1
l

louiscad

10/30/2020, 12:58 PM
LiveData
is Android only and doesn't come with
Flow
operators.
☝️ 1
a

Adam Powell

10/30/2020, 1:27 PM
Also LiveData isn't thread-safe and can only be mutated or observed on the main thread
e

Eric Ampire [MOD]

10/30/2020, 2:41 PM
Another question : Once the state changes, and the observer consumes or collects this new state, the channel becomes empty or it converts the last state. In other words, can StateFlow easily manage navigation between different views of the application?
a

Adam Powell

10/30/2020, 3:48 PM
no, for those cases you want something more like a channel or
channel.receiveAsFlow()
LiveData shouldn't be used for this either for similar reasons
but people try to put that square peg into the round hole anyway because there's no
LiveChannel
or similar 🙂
e

Eric Ampire [MOD]

10/30/2020, 4:24 PM
Okay thanks
2 Views