0

How can we handle in case multiple data sources update value to the same LiveData and observed by the view?

If we only want the result from the last button that user click and because the network call may have latency and the final result that update to the view may be from the first called.

Click Button-A → For Loading API#1 → post value to → LiveData<> A

Click Button-B → For Loading API#2 → post value to → LiveData<> A

ViewA → Observer on → LiveData<> A

Jongz Puangput
  • 5,527
  • 10
  • 58
  • 96
  • maybe something like this 1. change `LiveData` to `LiveData` where long would be timestamp of API call start... 2. After API returns check current LiveData timestamp with timestamp of API request 3. if it's greater do not post value ... instead timestamp you can use static counter (AtomicLong) – Selvin Mar 13 '19 at 11:22
  • That's true @Selvin (My suggestion wouldn't help in such case), I misunderstood question. – Jeel Vankhede Mar 13 '19 at 11:37
  • @Selvin actually it should be LIFO, ex, call sequech start Api A, B, B, A, B, A, B the result I need is B only the rest should be ignore or cancelled – Jongz Puangput Mar 13 '19 at 11:44
  • In terms of call order it's FIFO: ex: you have calls 1,2,3 ... results returns in order 2,3,1 ... you wana show 2, 3 ... and skip 1 – Selvin Mar 13 '19 at 12:12
  • Well, actually MediatorLiveData it's not so bad idea ... before every API call you may create new LiveData remove old one and add new to mediator (this replace operation should be thread safe/atomic) ... now every API call would have own LiveData but mediator would emit data from last added (because it would only contain one source at the time) – Selvin Mar 13 '19 at 12:26

0 Answers0