Queue like Subject in RxJava

前端 未结 3 1330
梦毁少年i
梦毁少年i 2020-12-29 06:06

I\'m looking for a Subject (or something similar) that can:

  1. Could receive items and hold them in a queue or buffer if there are no subscribers
  2. Once we
3条回答
  •  春和景丽
    2020-12-29 06:53

    I achieve the expected result creating a customized Observable that wraps a publish subject and handles emission cache if there's no subscribers attached. Check it out.

    public class ExampleUnitTest {
        @Test
        public void testSample() throws Exception {
            MyCustomObservable myCustomObservable = new MyCustomObservable();
    
            myCustomObservable.emit("1");
            myCustomObservable.emit("2");
            myCustomObservable.emit("3");
    
            Subscription subscription = myCustomObservable.subscribe(System.out::println);
    
            myCustomObservable.emit("4");
            myCustomObservable.emit("5");
    
            subscription.unsubscribe();
    
            myCustomObservable.emit("6");
            myCustomObservable.emit("7");
            myCustomObservable.emit("8");
    
            myCustomObservable.subscribe(System.out::println);
        }
    }
    
    class MyCustomObservable extends Observable {
        private static PublishSubject publishSubject = PublishSubject.create();
        private static List valuesCache = new ArrayList<>();
    
        protected MyCustomObservable() {
            super(subscriber -> {
                Observable.from(valuesCache)
                        .doOnNext(subscriber::onNext)
                        .doOnCompleted(valuesCache::clear)
                        .subscribe();
    
                publishSubject.subscribe(subscriber);
            });
        }
    
        public void emit(String value) {
            if (publishSubject.hasObservers()) {
                publishSubject.onNext(value);
            } else {
                valuesCache.add(value);
            }
        }
    }
    

    Hope that it helps!

    Best Regards.

提交回复
热议问题