https://kotlinlang.org logo
#flow
Title
# flow
r

rachael

11/30/2021, 5:42 PM
New to Flow and I'm wondering if anyone can point me towards some resources for a particular use case. I want a Repository that holds a List<Message>. These messages are fetched from a backend service via GET request, but can also be updated at any time by events that come in from a pub/sub service. Currently the result from the backend is a MutableLiveData, but increasingly we're seeing ConcurrentModificationExceptions because we need to read and potentially do some processing on the list while events are coming in and updating the list. It seems like Flow's streams of data might help here but it would be nice to look at some concrete examples.
c

Chris Fillmore

11/30/2021, 7:29 PM
You can see in the implementation, this just calls
compareAndSet()
in a loop:
Copy code
public inline fun <T> MutableStateFlow<T>.update(function: (T) -> T) {
    while (true) {
        val prevValue = value
        val nextValue = function(prevValue)
        if (compareAndSet(prevValue, nextValue)) {
            return
        }
    }
}
A made up example, based on your use case
Copy code
class MessagesOwner(private val pubsub: SomeEmitter<Messages>) {
  val messagesState = MutableStateFlow<List<Messages>?>(null)

  init {
    pubsub.on("messages") { messages ->
      messagesState.update {
        // Your logic here, to merge your messages or whatever
      }
    }
  }

  suspend fun loadMessagesFromGet() {
    val messagesFromGet: List<Messages> = /* do your GET */
    messagesState.update { messages ->
      // Your logic here, to merge your messages or whatever
    }
  }
}
Note that if you are updating a List you will do something like:
Copy code
messagesState.update { list ->
  list.toMutableList().apply {
    // Modify the list
  }
}
r

rachael

11/30/2021, 8:28 PM
Thanks! I'll experiment with this a bit.
3 Views