https://kotlinlang.org logo
Title
b

Bruno_

03/21/2020, 10:58 AM
how do you approach updating the view model during long running tasks? I have to crawl data from ~20 websites and display it as a list. Do I: • make an
update publisher
(new items are being pushed into it) • refresh the view model data every let's say 1s • try to implement it so that if the user get's to the end of the list, more items are loaded
:stackoverflow: 4
:google: 2
a

atlantis210

03/24/2020, 6:43 AM
I'd say that if it takes much time it means it is not the best approach to display it on screen. You'll have to rethink your screen. Maybe make a viewpager and display each data retrieved from each site on a single page... Otherwise, if you really want to do what you said, I suggest you use PagedList and update your item's list with LiveData each time an item is available
k

kyleg

03/25/2020, 4:41 AM
Sounds like a job for
MediatorLiveData
. Suppose you have 10 websites to crawl.
data class Website(val url: String)

val sitesToCrawl: List<Website> = TODO()

fun crawl(url: String): LiveData<List<PageData>> = TODO()

val observer = MediatorLiveData<List<PageData>>().apply { value = list() }

sitesToCrawl.forEach { site ->
  val ld = crawl(site.url)
  observer.addSource(ld) { list ->
    observer.value = observer.value+list
  }
}
Something like that. Can’t remember if I’m doing list concat correctly.
The approach with something like ArrowFx is similar and doesn’t require Android libraries.
b

Bruno_

03/25/2020, 9:48 AM
@atlantis210 it's doesn't take a lot of time to load, it's just I'm new to android and I don't know how to solve the problem, currently I use the first approach these tasks are long running but they are not blocking the main thread @forward many thanks for the tip, I didn't know about this class, will make use of it