- Learning RxJava
- Thomas Nield
- 347字
- 2021-07-02 22:22:56
take()
The take() operator has two overloads. One will take a specified number of emissions and then call onComplete() after it captures all of them. It will also dispose of the entire subscription so that no more emissions will occur. For instance, take(3) will emit the first three emissions and then call the onComplete() event:
import io.reactivex.Observable;
public class Launcher {
public static void main(String[] args) {
Observable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon")
.take(3)
.subscribe(s -> System.out.println("RECEIVED: " + s));
}
}
The output of the preceding code snippet is as follows:
RECEIVED: Alpha
RECEIVED: Beta
RECEIVED: Gamma
Note that if you receive fewer emissions than you specify in your take() function, it will simply emit what it does get and then call the onComplete() function.
The other overload will take emissions within a specific time duration and then call onComplete(). Of course, our cold Observable here will emit so quickly that it would serve as a bad example for this case. Maybe a better example would be to use an Observable.interval() function. Let's emit every 300 milliseconds, but take()emissions for only 2 seconds in the following code snippet:
import io.reactivex.Observable;
import java.util.concurrent.TimeUnit;
public class Launcher {
public static void main(String[] args) {
Observable.interval(300, TimeUnit.MILLISECONDS)
.take(2, TimeUnit.SECONDS)
.subscribe(i -> System.out.println("RECEIVED: " + i));
sleep(5000);
}
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The output of the preceding code snippet is as follows:
RECEIVED: 0
RECEIVED: 1
RECEIVED: 2
RECEIVED: 3
RECEIVED: 4
RECEIVED: 5
You will likely get the output that's shown here (each print happening every 300 milliseconds). You can only get six emissions in 2 seconds if they are spaced out by 300 milliseconds.
Note that there is also a takeLast() operator, which will take the last specified number of emissions (or time duration) before the onComplete() function is called. Just keep in mind that it will internally queue emissions until its onComplete() function is called, and then it can logically identify and emit the last emissions.
- Java虛擬機(jī)字節(jié)碼:從入門到實(shí)戰(zhàn)
- Functional Kotlin
- FLL+WRO樂高機(jī)器人競(jìng)賽教程:機(jī)械、巡線與PID
- Access 2010數(shù)據(jù)庫應(yīng)用技術(shù)(第2版)
- Java程序設(shè)計(jì)入門
- OpenStack Networking Essentials
- Orleans:構(gòu)建高性能分布式Actor服務(wù)
- C++ Fundamentals
- Solutions Architect's Handbook
- SQL Server 2016 從入門到實(shí)戰(zhàn)(視頻教學(xué)版)
- Mudbox 2013 Cookbook
- Mastering Unreal Engine 4.X
- 優(yōu)化驅(qū)動(dòng)的設(shè)計(jì)方法
- 數(shù)據(jù)結(jié)構(gòu)與算法詳解
- C++從零開始學(xué)(視頻教學(xué)版)(第2版)