Get the latest value of an Observable and emit it immeditely

前端 未结 3 1014
渐次进展
渐次进展 2021-02-12 09:13

I\'m trying to get the latest value of a given Observable and get it to emit immediately once it\'s called. Given the code below as an example:

ret         


        
3条回答
  •  执笔经年
    2021-02-12 10:14

    What you actually want to achieve here is to take an asynchronous task and transform it to a synchronous one.

    There are several ways to achieve it, each one with it's pros and cons:

    • Use toBlocking() - it means that this thread will be BLOCKED, until the stream is finish, in order to get only one item simply use first() as it will complete once an item is delivered. let's say your entire stream is Observable getData(); then a method that will get the last value immediately will look like this:

    public T getLastItem(){ return getData().toBlocking().first(); }

    please don't use last() as it will wait for the stream to complete and only then will emit the last item.

    If your stream is a network request and it didn't get any item yet this will block your thread!, so only use it when you are sure that there is an item available immediately (or if you really want a block...)

    • another option is to simply cache the last result, something like this:

      getData().subscribe(t-> cachedT = t;) //somewhere in the code and it will keep saving the last item delivered public T getLastItem(){ return cachedT; }

    if there wasn't any item sent by the time you request it you will get null or whatever initial value you have set. the problem with this approch is that the subscribe phase might happen after the get and might make a race condition if used in 2 different threads.

提交回复
热议问题