Get the latest value of an Observable and emit it immeditely

前端 未结 3 1015
渐次进展
渐次进展 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 09:58

    In RxJava, subscriber.onXXX is called asynchronous.It means that if your Observable emit items in new thread, you can never get the last item before return, except you block the thread and wait for the item.But if the Observable emit item synchronously and you dont' change it's thread by subscribeOn and observOn, such as the code:

    Observable.just(1,2,3).subscribe();
    

    In this case, you can get the last item by doing like this:

    Integer getLast(Observable o){
        final int[] ret = new int[1];
        Observable.last().subscribe(i -> ret[0] = i);
        return ret[0];
    }
    

    It's a bad idea doing like this.RxJava prefer you to do asynchronous work by it.

提交回复
热议问题