3 Commits

Author SHA1 Message Date
haerong22
62ae48c8a0 add front end 2022-10-15 23:39:41 +09:00
haerong22
b8d7190637 #24 simple sns: init 2022-10-14 03:18:16 +09:00
haerong22
3ee0825b48 start 2022-10-14 03:08:12 +09:00
4693 changed files with 282 additions and 1002342 deletions

332
.gitignore vendored
View File

@@ -1,72 +1,288 @@
.gradle # Created by https://www.toptal.com/developers/gitignore/api/intellij,intellij+all,intellij+iml,gradle,java
build/ # Edit at https://www.toptal.com/developers/gitignore?templates=intellij,intellij+all,intellij+iml,gradle,java
target/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ### ### Intellij ###
.apt_generated # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
.classpath # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ### # User-specific stuff
.idea .idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws *.iws
*.iml
*.ipr # IntelliJ
out/ out/
!**/src/main/**/out/
!**/src/test/**/out/
# Compliled files # mpeltonen/sbt-idea plugin
/target/ .idea_modules/
**/target
### NetBeans ### # JIRA plugin
/nbproject/private/ atlassian-ide-plugin.xml
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ### # Cursive Clojure plugin
.vscode/ .idea/replstate.xml
### Node ### # SonarLint plugin
dev.js .idea/sonarlint/
# dependencies # Crashlytics plugin (for Android Studio and IntelliJ)
/node_modules com_crashlytics_export_strings.xml
/.pnp crashlytics.properties
.pnp.js crashlytics-build.properties
fabric.properties
# testing # Editor-based Rest Client
/coverage .idea/httpRequests
# production # Android studio 3.1+ serialized cache file
/build .idea/caches/build_file_checksums.ser
# misc ### Intellij Patch ###
.DS_Store # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log* # *.iml
yarn-debug.log* # modules.xml
yarn-error.log* # .idea/misc.xml
# *.ipr
**/node_modules/** # Sonarlint plugin
**/.secret # https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml
### Intellij+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
# AWS User-specific
# Generated files
# Sensitive or high-churn files
# Gradle
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
# Mongo Explorer plugin
# File-based project format
# IntelliJ
# mpeltonen/sbt-idea plugin
# JIRA plugin
# Cursive Clojure plugin
# SonarLint plugin
# Crashlytics plugin (for Android Studio and IntelliJ)
# Editor-based Rest Client
# Android studio 3.1+ serialized cache file
### Intellij+all Patch ###
# Ignore everything but code style settings and run configurations
# that are supposed to be shared within teams.
.idea/*
!.idea/codeStyles
!.idea/runConfigurations
### Intellij+iml ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
# AWS User-specific
# Generated files
# Sensitive or high-churn files
# Gradle
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
# Mongo Explorer plugin
# File-based project format
# IntelliJ
# mpeltonen/sbt-idea plugin
# JIRA plugin
# Cursive Clojure plugin
# SonarLint plugin
# Crashlytics plugin (for Android Studio and IntelliJ)
# Editor-based Rest Client
# Android studio 3.1+ serialized cache file
### Intellij+iml Patch ###
# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023
*.iml
modules.xml
.idea/misc.xml
*.ipr
### Java ###
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
### Gradle ###
.gradle
**/build/
!src/**/build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Avoid ignore Gradle wrappper properties
!gradle-wrapper.properties
# Cache of project
.gradletasknamecache
# Eclipse Gradle plugin generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
### Gradle Patch ###
# Java heap dump
*.hprof
# End of https://www.toptal.com/developers/gitignore/api/intellij,intellij+all,intellij+iml,gradle,java
**/front-end/node_modules/**
**/front-end/static/**

View File

@@ -1,21 +0,0 @@
plugins {
id 'java'
}
group 'com.rxjava'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation 'io.reactivex.rxjava3:rxjava:3.1.3'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
test {
useJUnitPlatform()
}

View File

@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,185 +0,0 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MSYS* | MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

View File

@@ -1,89 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,2 +0,0 @@
rootProject.name = 'ReactiveStream'

View File

@@ -1,41 +0,0 @@
package _01_start;
import io.reactivex.rxjava3.core.Flowable;
import java.util.concurrent.TimeUnit;
public class AsyncEx {
private enum State {
ADD, MULTIPLY
}
private static State calcMethod;
public static void main(String[] args) throws InterruptedException {
calcMethod = State.ADD;
Flowable<Long> flowable =
Flowable.interval(300L, TimeUnit.MILLISECONDS)
.take(7)
.scan((sum, data) -> {
if (calcMethod == State.ADD) {
return sum + data;
} else {
return sum * data;
}
});
// 구독 후 받은 데이터 출력
flowable.subscribe(data -> System.out.println("data = " + data));
// Sleep 후 계산법 변경
// Bad case -> 외부의 데이터가 계산에 영향을 주면 안된다.
Thread.sleep(1000);
System.out.println("계산법 변경");
calcMethod = State.MULTIPLY;
Thread.sleep(2000);
}
}

View File

@@ -1,15 +0,0 @@
package _01_start;
import io.reactivex.rxjava3.core.Flowable;
public class ColdPublisherEx {
public static void main(String[] args) {
Flowable<Integer> flowable = Flowable.just(1, 2, 3, 4);
// 구독시 처음부터 타임라인을 재구성하여 모든 데이터를 받을 수 있다.
flowable.subscribe(data -> System.out.println("data = " + data));
flowable.subscribe(data -> System.out.println("data = " + data));
}
}

View File

@@ -1,20 +0,0 @@
package _01_start;
import io.reactivex.rxjava3.processors.PublishProcessor;
public class HotPublisherEx {
public static void main(String[] args) {
PublishProcessor<Integer> processor = PublishProcessor.create();
processor.subscribe(data -> System.out.println("subscribe1 = " + data));
processor.onNext(1);
processor.onNext(2);
// 구독한 시점 이후의 데이터만 받을 수 있다.
processor.subscribe(data -> System.out.println("subscribe2 = " + data));
processor.onNext(3);
processor.onNext(4);
}
}

View File

@@ -1,16 +0,0 @@
package _01_start;
import io.reactivex.rxjava3.core.Flowable;
public class OperatorEx {
public static void main(String[] args) {
Flowable<Integer> flowable =
Flowable.just(1, 2, 3, 4, 5, 6, 7, 8)
.filter(data -> data % 2 == 0 )
.map(data -> data * 2);
flowable.subscribe(data -> System.out.println("data = " + data));
}
}

View File

@@ -1,76 +0,0 @@
package _02_backpressure;
import io.reactivex.rxjava3.core.BackpressureOverflowStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.util.concurrent.TimeUnit;
public class BackPressureStrategyEx {
/*
BUFFER : 모든 데이터 버퍼링
DROP : 새로 생성한 데이터 삭제
LATEST : 버퍼가 비워질 때 까지 통지 데이터 대기
ERROR : 버퍼 크기 초과시 MissingBackpressureException
NONE : 특정 처리 수행 X
*/
public static void main(String[] args) throws InterruptedException {
// BUFFER 전략
// bufferStrategy();
// DROP 전략
// dropStrategy();
// LATEST 전략
latestStrategy();
Thread.sleep(3000L);
}
private static void latestStrategy() {
Flowable.interval(300L, TimeUnit.MILLISECONDS)
.doOnNext(data -> System.out.println("interval = " + data))
.onBackpressureLatest()
.observeOn(Schedulers.computation(), false, 1)
.subscribe(
data -> {
Thread.sleep(1000L);
System.out.println("data = " + data);
},
error -> System.out.println("error = " + error)
);
}
private static void dropStrategy() {
Flowable.interval(300L, TimeUnit.MILLISECONDS)
.doOnNext(data -> System.out.println("interval = " + data))
.onBackpressureDrop(drop -> System.out.println("drop = " + drop))
.observeOn(Schedulers.computation(), false, 1)
.subscribe(
data -> {
Thread.sleep(1000L);
System.out.println("data = " + data);
},
error -> System.out.println("error = " + error)
);
}
private static void bufferStrategy() {
Flowable.interval(300L, TimeUnit.MILLISECONDS)
.doOnNext(data -> System.out.println("interval = " + data))
.onBackpressureBuffer(
2,
() -> System.out.println("overflow"),
BackpressureOverflowStrategy.DROP_LATEST // ERROR, DROP_LATEST, DROP_OLDEST
)
.doOnNext(data -> System.out.println("buffer = " + data))
.observeOn(Schedulers.computation(), false, 1)
.subscribe(
data -> {
Thread.sleep(1000L);
System.out.println("data = " + data);
},
error -> System.out.println("error = " + error)
);
}
}

View File

@@ -1,30 +0,0 @@
package _02_backpressure;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.util.concurrent.TimeUnit;
public class MissingBackpressureExceptionEx {
public static void main(String[] args) throws InterruptedException {
/*
실행시 통지 속도보다 처리 속도가 느리기 때문에 MissingBackpressureException 발생
기본 버퍼가 128 이므로 128이상의 통지가 오면 예외발생
*/
Flowable.interval(1L, TimeUnit.MILLISECONDS) // 1ms 마다 숫자 통지
.doOnNext(data -> System.out.println("data = " + data)) // 통지된 데이터 출력
.observeOn(Schedulers.computation())
.subscribe(
data -> {
System.out.println("처리 대기중");
Thread.sleep(1000L); // 1초의 지연
System.out.println("data = " + data);
},
error -> System.out.println("error = " + error),
() -> System.out.println("completed")
);
Thread.sleep(2000L);
}
}

View File

@@ -1,53 +0,0 @@
package _03_basic;
import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
public class FlowableEx {
public static void main(String[] args) {
Flowable<String> flowable = Flowable.create(emitter -> {
String[] data = {"Hello, World!", "Hello, RxJava!"};
for (String d : data) {
if (emitter.isCancelled()) {
return;
}
emitter.onNext(d);
}
emitter.onComplete();
}, BackpressureStrategy.BUFFER);
flowable.observeOn(Schedulers.computation())
.subscribe(new Subscriber<String>() {
private Subscription subscription;
@Override
public void onSubscribe(Subscription s) {
this.subscription = s;
this.subscription.request(1L); // 데이터 개수 요청
}
@Override
public void onNext(String s) {
System.out.println(s);
this.subscription.request(1L); // 다음에 받을 데이터 개수 요청
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
System.out.println("complete");
}
});
}
}

View File

@@ -1,52 +0,0 @@
package _03_basic;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class ObservableEx {
public static void main(String[] args) {
/*
observable 은 배압이 없기 때문에 데이터가 생성 될 때마다 바로 통지된다.
*/
Observable<String> observable = Observable.create(emitter -> {
String[] data = {"Hello, World!", "Hello, RxJava!"};
for (String d : data) {
if (emitter.isDisposed()) {
return;
}
emitter.onNext(d);
}
emitter.onComplete();
});
observable.observeOn(Schedulers.computation())
.subscribe(new Observer<String>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
// 구독 중 구독을 해지하려면 전달받은 Disposable 을 내부에 보관(dispose 메소드 호출)
}
@Override
public void onNext(@NonNull String s) {
System.out.println(s);
}
@Override
public void onError(@NonNull Throwable e) {
e.printStackTrace();
}
@Override
public void onComplete() {
System.out.println("complete");
}
});
}
}

View File

@@ -1,11 +0,0 @@
### Flowable, Observable
- Flowable : 배압 기능이 있다. 대량 데이터 처리, 네트워크 처리, I/O 처리
- Observable : 배압 기능이 없다. 소량 데이터 처리
### 통지 규칙
- null을 통지하면 안된다.
- 데이터 통지는 Optional이다.
- 완료나 에러 통지를 한 뒤에는 다른 통지를 해서는 안 된다.
- 통지를 할 때는 1건씩 순차적으로 통지해야 하며 동시에 통지하면 안 된다.

View File

@@ -1,14 +0,0 @@
package _01_lambda;
public interface ExInterface {
void getMsg();
default String defaultMethod() {
return "default method";
}
static void print(String msg) {
System.out.println("msg = " + msg);
}
}

View File

@@ -1,17 +0,0 @@
package _01_lambda;
public class LambdaEx_01 {
public static void main(String[] args) {
ExInterface.print("interface static method test");
ExInterface exInterface = () -> System.out.println("implement abstract method");
exInterface.getMsg();
String result = exInterface.defaultMethod();
System.out.println("result = " + result);
}
}

View File

@@ -1,18 +0,0 @@
package _01_lambda;
public class LambdaEx_02 {
public static void main(String[] args) {
// 람다 사용 X
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Run Thread");
}
}).start();
// 람다 사용
new Thread(() -> System.out.println("Lambda Run Thread")).start();
}
}

View File

@@ -1,46 +0,0 @@
package _01_lambda;
public class LambdaEx_03 {
@FunctionalInterface
interface MyFunction1 {
int calc(int a);
}
@FunctionalInterface
interface MyFunction2 {
int calc(int a, int b);
}
@FunctionalInterface
interface MyFunction3 {
void print();
}
public static void main(String[] args) {
// 파라미터가 1개인 람다식
MyFunction1 result1 = (x) -> { return x + x; };
MyFunction1 result2 = x -> x + x; // 괄호 생략 가능
System.out.println("result1 = " + result1.calc(5));
System.out.println("result2 = " + result2.calc(5));
// 파라미터가 2개인 람다식
MyFunction2 add = (x, y) -> x + y;
MyFunction2 minus = (x, y) -> x - y;
System.out.println("add = " + add.calc(1, 2));
System.out.println("minus = " + minus.calc(1, 2));
// 파라미터가 없는 람다식
MyFunction3 myFunction3 = () -> System.out.println("print method");
myFunction3.print();
// 함수형 인터페이스 파라미터로 전달
printSum(3, 4, (x, y) -> x * y);
}
static void printSum(int x, int y, MyFunction2 f) {
System.out.println(f.calc(x, y));
}
}

View File

@@ -1,14 +0,0 @@
package _01_lambda;
public class LambdaEx_04 {
@FunctionalInterface
interface MyFunction3 {
void print();
}
public static void main(String[] args) {
//
}
}

View File

@@ -1,83 +0,0 @@
package _02_functional_interface;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.*;
/**
* Function : T -> R
* Consumer : T -> void
* Supplier : void -> T
* Operator : T -> T
* Predicate : T -> boolean
*
*/
public class FunctionalInterfaceEx_01 {
public static void main(String[] args) {
// 예외 throw 불가능 -> try catch 구문을 이용하여 예외처리를 한다.
Function<BufferedReader, String> f = bufferedReader -> {
try {
return bufferedReader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
};
// Predicate 사용
List<String> list = Arrays.asList("", "test1", "test2", "test3", "");
List<String> result = filter(list, s -> !s.isEmpty()); // 리스트의 공백을 제거하는 predicate 전달
System.out.println("list = " + list);
System.out.println("result = " + result);
// Consumer 사용
List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5);
forEach(list2, i -> System.out.println(i)); // 리스트 값 출력하는 consumer 전달
// Function 사용
List<String> list3 = Arrays.asList("test1", "test22", "test333");
List<Integer> result3 = map(list3, s -> s.length()); // 각 요소의 길이 출력
System.out.println("result3 = " + result3);
// Operator 사용
UnaryOperator<String> u = str -> str + " test";
String result4 = u.apply("operator");
System.out.println("result4 = " + result4);
// Supplier 사용
Supplier<String> s = () -> "supplier";
String result5 = s.get();
System.out.println("result5 = " + result5);
}
public static <T, R> List<R> map(List<T> list, Function<T, R> f) {
List<R> result = new ArrayList<>();
for (T t : list) {
result.add(f.apply(t));
}
return result;
}
public static <T> void forEach(List<T> list, Consumer<T> c) {
for (T t : list) {
c.accept(t);
}
}
public static <T> List<T> filter(List<T> list, Predicate<T> p) {
final List<T> result = new ArrayList<>();
for (T t : list) {
if (p.test(t)) {
result.add(t);
}
}
return result;
}
}

View File

@@ -1,55 +0,0 @@
package _03_stream;
import java.util.Arrays;
import java.util.List;
public class Dish {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;
public Dish(String name, boolean vegetarian, int calories, Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}
public String getName() {
return name;
}
public boolean isVegetarian() {
return vegetarian;
}
public int getCalories() {
return calories;
}
public Type getType() {
return type;
}
public enum Type {
MEAT, FISH, OTHER
}
@Override
public String toString() {
return name;
}
public static final List<Dish> menu = Arrays.asList(
new Dish("돼지고기", false, 800, Type.MEAT),
new Dish("소고기", false, 700, Type.MEAT),
new Dish("닭고기", false, 400, Type.MEAT),
new Dish("감자 튀김", true, 530, Type.OTHER),
new Dish("", true, 350, Type.OTHER),
new Dish("계절 과일", true, 120, Type.OTHER),
new Dish("피자", true, 550, Type.OTHER),
new Dish("연어", false, 450, Type.FISH)
);
}

View File

@@ -1,28 +0,0 @@
package _03_stream;
import java.util.Arrays;
public class StreamEx_01 {
public static void main(String[] args) {
String[] words = {"a", "bc", "def"};
// stream 사용 X
int count = 0;
for (String word : words) {
if (word.length() > 2) {
count++;
}
}
System.out.println("count = " + count);
// stream 사용
long streamCount = Arrays.stream(words)
.filter(word -> word.length() > 2)
.count();
System.out.println("streamCount = " + streamCount);
}
}

View File

@@ -1,21 +0,0 @@
package _03_stream;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamEx_02 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// 스트림 생성
Stream<Integer> stream = list.stream(); // Collection
Stream<String> stringStream = Stream.of("a", "b", "c");// 배열
Stream<Double> ranStream = Stream.generate(Math::random); // 메소드 레퍼런스
IntStream intStream = new Random().ints(5); // 난수 스트림
}
}

View File

@@ -1,26 +0,0 @@
package _03_stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class StreamEx_03 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(3, 1, 5, 4, 2);
List<Integer> sortedList = list.stream()
.sorted() // 정렬
.toList(); // 새로운 List 에 저장
System.out.println("list = " + list);
System.out.println("sortedList = " + sortedList);
String[] words = {"a", "bc", "def"};
Stream<String> stream = Arrays.stream(words);
stream.forEach(System.out::println);
// long count = stream.count(); // 재사용 불가
// System.out.println("count = " + count);
}
}

View File

@@ -1,15 +0,0 @@
package _03_stream;
import java.util.stream.Stream;
public class StreamEx_04 {
public static void main(String[] args) {
Stream<String> stringStream = Stream.of("aa", "bb", "cc", "dd", "ee");
int sum = stringStream.parallel() // 병렬 스트림으로 전환
.mapToInt(String::length).sum();
System.out.println("sum = " + sum);
}
}

View File

@@ -1,17 +0,0 @@
package _03_stream;
import java.util.List;
public class StreamEx_05 {
public static void main(String[] args) {
List<String> names = Dish.menu.stream()
.filter(dish -> dish.getCalories() > 300)
.map(Dish::getName)
.limit(3)
.toList();
System.out.println("names = " + names);
}
}

View File

@@ -1,16 +0,0 @@
package _03_stream;
import java.util.List;
public class StreamEx_06 {
public static void main(String[] args) {
List<Dish> vegetarianMenu = Dish.menu.stream()
.filter(Dish::isVegetarian)
.toList();
System.out.println("vegetarianMenu = " + vegetarianMenu);
}
}

View File

@@ -1,18 +0,0 @@
package _03_stream;
import java.util.Arrays;
import java.util.List;
public class StreamEx_07 {
public static void main(String[] args) {
// distinct -> hashCode, equals 로 결정
List<Integer> list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
list.stream()
.filter(i -> i % 2 == 0)
.distinct()
.forEach(System.out::println);
}
}

View File

@@ -1,17 +0,0 @@
package _03_stream;
import java.util.List;
public class StreamEx_08 {
public static void main(String[] args) {
// skip(n) n번째 요소 이후의 요소만 선택, 없으면 빈배열
List<Dish> dishes = Dish.menu.stream()
.filter(dish -> dish.getCalories() > 300)
.skip(2)
.toList();
System.out.println("dishes = " + dishes);
}
}

View File

@@ -1,29 +0,0 @@
package _03_stream;
import java.util.Arrays;
import java.util.List;
public class StreamEx_09 {
public static void main(String[] args) {
// map -> 다른 타입으로 변환
List<Integer> result = Dish.menu.stream()
.map(Dish::getName)// Dish -> String
.map(String::length)// String -> Integer
.toList();
System.out.println("result = " + result);
// flatMap
List<String> words = Arrays.asList("Hello", "world");
List<String> uniqueCharacter = words.stream()
.map(word -> word.split("")) // String -> String[] 이 되므로 Stream<String[]>
.flatMap(Arrays::stream) // Stream<String>
.distinct()
.toList();
System.out.println("uniqueCharacter = " + uniqueCharacter);
}
}

View File

@@ -1,35 +0,0 @@
package _03_stream;
import java.util.Optional;
public class StreamEx_10 {
public static void main(String[] args) {
if (isVegetarianFriendlyMenu()) {
System.out.println("Vegetarian friendly");
}
System.out.println(isHealthyMenu());
System.out.println(isHealthyMenu2());
findVegetarianDish()
.ifPresent(dish -> System.out.println(dish.getName()));
}
private static Optional<Dish> findVegetarianDish() {
return Dish.menu.stream().filter(Dish::isVegetarian).findAny();
}
private static boolean isHealthyMenu2() {
return Dish.menu.stream().noneMatch(dish -> dish.getCalories() >= 1000);
}
private static boolean isHealthyMenu() {
return Dish.menu.stream().allMatch(dish -> dish.getCalories() < 1000);
}
private static boolean isVegetarianFriendlyMenu() {
return Dish.menu.stream().anyMatch(Dish::isVegetarian);
}
}

View File

@@ -1,28 +0,0 @@
package _03_stream;
import java.util.Arrays;
import java.util.List;
public class StreamEx_11 {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(3, 4, 5, 1, 2);
Integer sum = numbers.stream().reduce(0, Integer::sum);
System.out.println("sum = " + sum);
numbers.stream().reduce(Math::min)
.ifPresent(System.out::println);
numbers.stream().reduce(Math::max)
.ifPresent(System.out::println);
List<String> strings = Arrays.asList("a", "b", "c");
strings.stream()
.filter(str -> !str.equals("b"))
.reduce((a, b) -> a + b)
.ifPresent(System.out::println);
}
}

View File

@@ -1,21 +0,0 @@
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
implementation 'io.reactivex.rxjava3:rxjava:3.1.6'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
test {
useJUnitPlatform()
}

Binary file not shown.

View File

@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,234 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@@ -1,89 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,2 +0,0 @@
rootProject.name = 'practice'

View File

@@ -1,73 +0,0 @@
package org.example.common;
public class Car {
private CarMaker carMaker;
private CarType carType;
private String carName;
private int carPrice;
private boolean isNew;
public Car(String carName){
this.carName = carName;
}
public Car(String carName, CarType carType){
this.carName = carName;
this.carType = carType;
}
public Car(CarMaker carMaker, String carName, CarType carType, int carPrice){
this.carMaker = carMaker;
this.carName = carName;
this.carType = carType;
this.carPrice = carPrice;
}
public Car(CarMaker carMaker, CarType carType, String carName, int carPrice, boolean isNew) {
this.carMaker = carMaker;
this.carType = carType;
this.carName = carName;
this.carPrice = carPrice;
this.isNew = isNew;
}
public CarMaker getCarMaker() {
return carMaker;
}
public void setCarMaker(CarMaker carMaker) {
this.carMaker = carMaker;
}
public CarType getCarType() {
return carType;
}
public void setCarType(CarType carType) {
this.carType = carType;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public int getCarPrice() {
return carPrice;
}
public void setCarPrice(int carPrice) {
this.carPrice = carPrice;
}
public boolean isNew() {
return isNew;
}
public void setNew(boolean aNew) {
isNew = aNew;
}
}

View File

@@ -1,29 +0,0 @@
package org.example.common;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class CarFilter {
// 사용자 정의 Predicate 사용
public static List<Car> filterCarByCustomPredicate(List<Car> cars, CarPredicate p) {
List<Car> resultCars = new ArrayList<>();
for(Car car : cars)
if (p.test(car)) {
resultCars.add(car);
}
return resultCars;
}
// java.util.function 패키지에 내장된 Predicate 사용
public static List<Car> filterCarByBuiltinPredicate(List<Car> cars, Predicate<Car> p) {
List<Car> resultCars = new ArrayList<>();
for(Car car : cars)
if (p.test(car)) {
resultCars.add(car);
}
return resultCars;
}
}

View File

@@ -1,9 +0,0 @@
package org.example.common;
public enum CarMaker {
HYUNDAE,
CHEVROLET,
KIA,
SSANGYOUNG,
SAMSUNG
}

View File

@@ -1,5 +0,0 @@
package org.example.common;
public interface CarPredicate {
boolean test(Car car);
}

View File

@@ -1,7 +0,0 @@
package org.example.common;
public enum CarType {
SEDAN,
SUV,
PICKUPTRUK
}

View File

@@ -1,96 +0,0 @@
package org.example.common;
import io.reactivex.rxjava3.core.Observable;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class SampleData {
public static CarMaker[] carMakersDuplicated = {
CarMaker.CHEVROLET,
CarMaker.HYUNDAE,
CarMaker.SAMSUNG,
CarMaker.SSANGYOUNG,
CarMaker.CHEVROLET,
CarMaker.HYUNDAE,
CarMaker.KIA,
CarMaker.SSANGYOUNG
};
public static CarMaker[] carMakers = {
CarMaker.CHEVROLET,
CarMaker.HYUNDAE,
CarMaker.SAMSUNG,
CarMaker.SSANGYOUNG,
CarMaker.KIA
};
public static List<Car> carList =
Arrays.asList(
new Car(CarMaker.CHEVROLET, "말리부", CarType.SEDAN, 23_000_000),
new Car(CarMaker.HYUNDAE, "쏘렌토", CarType.SUV, 33_000_000),
new Car(CarMaker.CHEVROLET, "트래버스", CarType.SUV, 50_000_000),
new Car(CarMaker.HYUNDAE, "팰리세이드", CarType.SEDAN, 28_000_000),
new Car(CarMaker.CHEVROLET, "트랙스", CarType.SUV, 18_000_000),
new Car(CarMaker.SSANGYOUNG, "티볼리", CarType.SUV, 23_000_000),
new Car(CarMaker.SAMSUNG, "SM6", CarType.SUV, 40_000_000),
new Car(CarMaker.SSANGYOUNG, "G4렉스턴", CarType.SUV, 43_000_000),
new Car(CarMaker.SAMSUNG, "SM5", CarType.SEDAN, 35_000_000)
);
// A, B, C 구간의 차량 속도 데이터
public static final Integer[] speedOfSectionA = {100, 110, 115, 130, 160};
public static final Integer[] speedOfSectionB = {85, 90, 100, 110, 105, 113, 125};
public static final Integer[] speedOfSectionC = {98, 88, 111, 123, 155, 124, 136, 143};
// 지점 A의 월별 매출
public static final List<Integer> salesOfBranchA = Arrays.asList(
15_000_000, 25_000_000, 10_000_000, 35_000_000, 23_000_000, 40_000_000, 50_000_000, 45_000_000,
35_000_000, 23_000_000, 15_000_000, 10_000_000
);
// 지점 B의 월별 매출
public static final List<Integer> salesOfBranchB = Arrays.asList(
11_000_000, 23_000_000, 15_000_000, 32_000_000, 13_000_000, 45_000_000, 55_000_000, 43_000_000,
25_000_000, 28_000_000, 19_000_000, 13_000_000
);
// 지점 C의 월별 매출
public static final List<Integer> salesOfBranchC = Arrays.asList(
12_000_000, 21_000_000, 19_000_000, 33_000_000, 33_000_000, 41_000_000, 52_000_000, 48_000_000,
32_000_000, 21_000_000, 18_000_000, 14_000_000
);
// 서울의 시간별 미세먼지 농도
public static final List<Integer> seoulPM10List = Arrays.asList(
45, 30, 68, 70, 100, 110, 120, 90, 80, 60, 50, 60, 70, 80, 100, 150, 140, 130, 170, 130, 90, 86, 67, 50
);
// 부산의 시간별 미세먼지 농도
public static final List<Integer> busanPM10List = Arrays.asList(
35, 30, 63, 50, 80, 90, 100, 80, 70, 50, 55, 60, 65, 75, 80, 90, 100, 90, 120, 110, 70, 66, 65, 55
);
// 인천의 시간별 미세먼지 농도
public static final List<Integer> incheonPM10List = Arrays.asList(
55, 40, 73, 70, 85, 99, 120, 85, 75, 73, 80, 70, 95, 95, 100, 120, 110, 120, 140, 120, 100, 125, 135, 125
);
// 1시간 동안 서울의 온도 변화 데이터
public static Integer[] temperatureOfSeoul = {10, 13, 14, 12, 11, 9};
// 1시간 동안 서울의 습도 변화 데이터
public static Integer[] humidityOfSeoul = {45, 35, 33, 43, 32, 62};
public static Observable<String> getSpeedPerSection(String section, long interval, final Integer[] speedData){
return Observable.interval(interval, TimeUnit.MILLISECONDS)
.take(speedData.length)
.map(Long::intValue)
.map(i -> section + " 지점의 차량 속도: " + speedData[i]);
}
}

View File

@@ -1,19 +0,0 @@
package org.example.ex01;
import java.util.Arrays;
import java.util.List;
public class DeclarativePrograming {
public static void main(String[] args){
// List에 있는 숫자들 중에서 6보다 큰 홀수들의 합계를 구하세요.
List<Integer> numbers = Arrays.asList(1, 3, 21, 10, 8, 11);
int sum = numbers.stream()
.filter(number -> number > 6 && (number % 2 != 0))
.mapToInt(number -> number)
.sum();
System.out.println("# 선언형 프로그래밍 사용: " + sum);
}
}

View File

@@ -1,21 +0,0 @@
package org.example.ex01;
import java.util.Arrays;
import java.util.List;
public class ImperativeProgramming {
public static void main(String[] args){
// List에 있는 숫자들 중에서 6보다 큰 홀수들의 합계를 구하세요.
List<Integer> numbers = Arrays.asList(1, 3, 21, 10, 8, 11);
int sum = 0;
for(int number : numbers){
if(number > 6 && (number % 2 != 0)){
sum += number;
}
}
System.out.println("# 명령형 프로그래밍 사용: " + sum);
}
}

View File

@@ -1,18 +0,0 @@
package org.example.ex01;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class ReactiveProgramming {
public static void main(String[] args) throws InterruptedException {
Observable.just(100, 200, 300, 400, 500)
.doOnNext(data -> System.out.println(Thread.currentThread().getName() + " : #doOnNext() : " + data))
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.filter(number -> number > 300)
.subscribe(num -> System.out.println(Thread.currentThread().getName() + " : result : " + num));
Thread.sleep(500);
}
}

View File

@@ -1,12 +0,0 @@
package org.example.ex02;
import io.reactivex.rxjava3.core.Observable;
public class MarbleExample01 {
public static void main(String[] args) {
Observable.just(1, 25, 9, 15, 7, 30)
.filter(x -> x > 10)
.subscribe(System.out::println);
}
}

View File

@@ -1,12 +0,0 @@
package org.example.ex02;
import io.reactivex.rxjava3.core.Observable;
public class MarbleExample02 {
public static void main(String[] args) {
Observable<Integer> observable = Observable.just(1, 25, 9, 15, 7, 30);
observable.subscribe(System.out::println);
}
}

View File

@@ -1,13 +0,0 @@
package org.example.ex03;
import io.reactivex.rxjava3.core.Flowable;
public class ColdPublisherEx {
public static void main(String[] args) {
Flowable<Integer> flowable = Flowable.just(1, 3, 5, 7);
flowable.subscribe(data -> System.out.println("구독자1: " + data));
flowable.subscribe(data -> System.out.println("구독자2: " + data));
}
}

View File

@@ -1,19 +0,0 @@
package org.example.ex03;
import io.reactivex.rxjava3.processors.PublishProcessor;
public class HotPublisherEx {
public static void main(String[] args) {
PublishProcessor<Integer> processor = PublishProcessor.create();
processor.subscribe(data -> System.out.println("구독자1: " + data));
processor.onNext(1);
processor.onNext(3);
processor.subscribe(data -> System.out.println("구독자2: " + data));
processor.onNext(5);
processor.onNext(7);
processor.onComplete();
}
}

View File

@@ -1,35 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.BackpressureOverflowStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
import java.util.concurrent.TimeUnit;
public class BackpressureBufferEx01 {
public static void main(String[] args) {
System.out.println("# start : " + TimeUtil.getCurrentTimeFormatted());
Flowable.interval(300L, TimeUnit.MILLISECONDS)
.doOnNext(data -> Logger.log("#interval doOnNext()", data))
.onBackpressureBuffer(
2,
() -> Logger.log("overflow!"),
BackpressureOverflowStrategy.DROP_LATEST
)
.doOnNext(data -> Logger.log("#onBackpressureBuffer doOnNext()", data))
.observeOn(Schedulers.computation(), false, 1)
.subscribe(
data -> {
TimeUtil.sleep(1000L);
Logger.log(LogType.ON_NEXT, data);
},
error -> Logger.log(LogType.ON_ERROR, error)
);
TimeUtil.sleep(2800L);
}
}

View File

@@ -1,35 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.BackpressureOverflowStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
import java.util.concurrent.TimeUnit;
public class BackpressureBufferEx02 {
public static void main(String[] args) {
System.out.println("# start : " + TimeUtil.getCurrentTimeFormatted());
Flowable.interval(300L, TimeUnit.MILLISECONDS)
.doOnNext(data -> Logger.log("#interval doOnNext()", data))
.onBackpressureBuffer(
2,
() -> Logger.log("overflow!"),
BackpressureOverflowStrategy.DROP_OLDEST
)
.doOnNext(data -> Logger.log("#onBackpressureBuffer doOnNext()", data))
.observeOn(Schedulers.computation(), false, 1)
.subscribe(
data -> {
TimeUtil.sleep(1000L);
Logger.log(LogType.ON_NEXT, data);
},
error -> Logger.log(LogType.ON_ERROR, error)
);
TimeUtil.sleep(2800L);
}
}

View File

@@ -1,29 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
import java.util.concurrent.TimeUnit;
public class BackpressureDropEx {
public static void main(String[] args) {
System.out.println("# start : " + TimeUtil.getCurrentTimeFormatted());
Flowable.interval(300L, TimeUnit.MILLISECONDS)
.doOnNext(data -> Logger.log("#interval doOnNext()", data))
.onBackpressureDrop(dropData -> Logger.log(LogType.PRINT, dropData + " Drop!"))
.observeOn(Schedulers.computation(), false, 1)
.subscribe(
data -> {
TimeUtil.sleep(1000L);
Logger.log(LogType.ON_NEXT, data);
},
error -> Logger.log(LogType.ON_ERROR, error)
);
TimeUtil.sleep(5500L);
}
}

View File

@@ -1,29 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
import java.util.concurrent.TimeUnit;
public class BackpressureLatestEx {
public static void main(String[] args) {
System.out.println("# start : " + TimeUtil.getCurrentTimeFormatted());
Flowable.interval(300L, TimeUnit.MILLISECONDS)
.doOnNext(data -> Logger.log("#interval doOnNext()", data))
.onBackpressureLatest()
.observeOn(Schedulers.computation(), false, 1)
.subscribe(
data -> {
TimeUtil.sleep(1000L);
Logger.log(LogType.ON_NEXT, data);
},
error -> Logger.log(LogType.ON_ERROR, error)
);
TimeUtil.sleep(5500L);
}
}

View File

@@ -1,63 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.FlowableEmitter;
import io.reactivex.rxjava3.core.FlowableOnSubscribe;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
public class HelloRxJavaFlowableCreateEx {
public static void main(String[] args) throws InterruptedException {
Flowable<String> flowable =
Flowable.create(new FlowableOnSubscribe<String>() {
@Override
public void subscribe(FlowableEmitter<String> emitter) throws Exception {
String[] datas = {"Hello", "RxJava!"};
for(String data : datas) {
// 구독이 해지되면 처리 중단
if (emitter.isCancelled())
return;
// 데이터 통지
emitter.onNext(data);
}
// 데이터 통지 완료를 알린다
emitter.onComplete();
}
}, BackpressureStrategy.BUFFER); // 구독자의 처리가 늦을 경우 데이터를 버퍼에 담아두는 설정.
flowable.observeOn(Schedulers.computation())
.subscribe(new Subscriber<String>() {
// 데이터 개수 요청 및 구독을 취소하기 위한 Subscription 객체
private Subscription subscription;
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
this.subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(String data) {
Logger.log(LogType.ON_NEXT, data);
}
@Override
public void onError(Throwable error) {
Logger.log(LogType.ON_ERROR, error);
}
@Override
public void onComplete() {
Logger.log(LogType.ON_COMPLETE);
}
});
Thread.sleep(500L);
}
}

View File

@@ -1,38 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.BackpressureStrategy;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
public class HelloRxJavaFlowableCreateLambdaEx {
public static void main(String[] args) throws InterruptedException {
Flowable<String> flowable =
Flowable.create(emitter -> {
String[] datas = {"Hello", "RxJava!"};
for(String data : datas) {
// 구독이 해지되면 처리 중단
if (emitter.isCancelled())
return;
// 데이터 발행
emitter.onNext(data);
}
// 데이터 발행 완료를 알린다
emitter.onComplete();
}, BackpressureStrategy.BUFFER);
flowable.observeOn(Schedulers.computation())
.subscribe(
data -> Logger.log(LogType.ON_NEXT, data),
error -> Logger.log(LogType.ON_ERROR, error),
() -> Logger.log(LogType.ON_COMPLETE)
);
Thread.sleep(500L);
}
}

View File

@@ -1,54 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class HelloRxJavaObservableCreateEx {
public static void main(String[] args) throws InterruptedException {
Observable<String> observable =
Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> emitter) throws Exception {
String[] datas = {"Hello", "RxJava!"};
for (String data : datas) {
if (emitter.isDisposed())
return;
emitter.onNext(data);
}
emitter.onComplete();
}
});
observable.observeOn(Schedulers.computation())
.subscribe(new Observer<>() {
@Override
public void onSubscribe(Disposable disposable) {
// 아무 처리도 하지 않음.
}
@Override
public void onNext(String data) {
Logger.log(LogType.ON_NEXT, data);
}
@Override
public void onError(Throwable error) {
Logger.log(LogType.ON_ERROR, error);
}
@Override
public void onComplete() {
Logger.log(LogType.ON_COMPLETE);
}
});
Thread.sleep(500L);
}
}

View File

@@ -1,33 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class HelloRxJavaObservableCreateLambdaEx {
public static void main(String[] args) throws InterruptedException {
Observable<String> observable =
Observable.create(emitter -> {
String[] datas = {"Hello", "RxJava!"};
for (String data : datas) {
if (emitter.isDisposed())
return;
emitter.onNext(data);
}
emitter.onComplete();
});
observable.observeOn(Schedulers.computation())
.subscribe(
data -> Logger.log(LogType.ON_NEXT, data),
error -> Logger.log(LogType.ON_NEXT, error),
() -> Logger.log(LogType.DO_ON_COMPLETE)
);
Thread.sleep(500L);
}
}

View File

@@ -1,29 +0,0 @@
package org.example.ex04;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
import java.util.concurrent.TimeUnit;
public class MissingBackpressureExceptionEx {
public static void main(String[] args) throws InterruptedException {
Flowable.interval(1L, TimeUnit.MILLISECONDS)
.doOnNext(data -> Logger.log(LogType.DO_ON_NEXT, data))
.observeOn(Schedulers.computation())
.subscribe(
data -> {
Logger.log(LogType.PRINT, "# 소비자 처리 대기 중..");
TimeUtil.sleep(1000L);
Logger.log(LogType.ON_NEXT, data);
},
error -> Logger.log(LogType.ON_ERROR, error),
() -> Logger.log(LogType.ON_COMPLETE)
);
Thread.sleep(2000L);
}
}

View File

@@ -1,52 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.CompletableEmitter;
import io.reactivex.rxjava3.core.CompletableObserver;
import io.reactivex.rxjava3.core.CompletableOnSubscribe;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
/**
* Completable 을 사용하여 어떤 작업을 수행한 후, 완료를 통지하는 예제
*/
public class CompletableCreateEx {
public static void main(String[] args) throws InterruptedException {
Completable completable = Completable.create(new CompletableOnSubscribe() {
@Override
public void subscribe(CompletableEmitter emitter) throws Exception {
// 데이터를 통지하는것이 아니라 특정 작업을 수행한 후, 완료를 통지한다.
int sum = 0;
for(int i =0; i < 100; i++){
sum += i;
}
Logger.log(LogType.PRINT, "# 합계: " + sum);
emitter.onComplete();
}
});
completable.subscribeOn(Schedulers.computation())
.subscribe(new CompletableObserver() {
@Override
public void onSubscribe(Disposable disposable) {
// 아무것도 하지 않음
}
@Override
public void onComplete() {
Logger.log(LogType.ON_COMPLETE);
}
@Override
public void onError(Throwable error) {
Logger.log(LogType.ON_ERROR, error);
}
});
TimeUtil.sleep(1000L);
}
}

View File

@@ -1,30 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
public class CompletableLamdaEx {
public static void main(String[] args){
Completable completable = Completable.create(emitter -> {
// 데이터를 발행하는것이 아니라 특정 작업을 수행한 후, 완료를 통지한다.
int sum = 0;
for(int i =0; i < 100; i++){
sum += i;
}
Logger.log(LogType.PRINT, "# 합계: " + sum);
emitter.onComplete();
});
completable.subscribeOn(Schedulers.computation())
.subscribe(
() -> Logger.log(LogType.ON_COMPLETE),
error -> Logger.log(LogType.ON_ERROR, error)
);
TimeUtil.sleep(1000L);
}
}

View File

@@ -1,48 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.MaybeEmitter;
import io.reactivex.rxjava3.core.MaybeObserver;
import io.reactivex.rxjava3.core.MaybeOnSubscribe;
import io.reactivex.rxjava3.disposables.Disposable;
import org.example.utils.DateUtil;
import org.example.utils.LogType;
import org.example.utils.Logger;
/**
* Maybe 클래스를 이용하여 데이터를 통지하는 예제
*/
public class MaybeCreateEx {
public static void main(String[] args){
Maybe<String> maybe = Maybe.create(new MaybeOnSubscribe<String>() {
@Override
public void subscribe(MaybeEmitter<String> emitter) throws Exception {
// emitter.onSuccess(DateUtil.getNowDate());
emitter.onComplete();
}
});
maybe.subscribe(new MaybeObserver<String>() {
@Override
public void onSubscribe(Disposable disposable) {
// 아무것도 하지 않음.
}
@Override
public void onSuccess(String data) {
Logger.log(LogType.ON_SUCCESS, "# 현재 날짜시각: " + data);
}
@Override
public void onError(Throwable error) {
Logger.log(LogType.ON_ERROR, error);
}
@Override
public void onComplete() {
Logger.log(LogType.ON_COMPLETE);
}
});
}
}

View File

@@ -1,20 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Single;
import org.example.utils.DateUtil;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class MaybeFromSingle {
public static void main(String[] args){
Single<String> single = Single.just(DateUtil.getNowDate());
Maybe.fromSingle(single)
.subscribe(
data -> Logger.log(LogType.ON_SUCCESS, "# 현재 날짜시각: " + data),
error -> Logger.log(LogType.ON_ERROR, error),
() -> Logger.log(LogType.ON_COMPLETE)
);
}
}

View File

@@ -1,23 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.core.Maybe;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class MaybeJustEx {
public static void main(String[] args){
// Maybe.just(DateUtil.getNowDate())
// .subscribe(
// data -> Logger.log(LogType.ON_SUCCESS, "# 현재 날짜시각: " + data),
// error -> Logger.log(LogType.ON_ERROR, error),
// () -> Logger.log(LogType.ON_COMPLETE)
// );
Maybe.empty()
.subscribe(
data -> Logger.log(LogType.ON_SUCCESS, data),
error -> Logger.log(LogType.ON_ERROR, error),
() -> Logger.log(LogType.ON_COMPLETE)
);
}
}

View File

@@ -1,21 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.core.Maybe;
import org.example.utils.DateUtil;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class MaybeLambdaEx {
public static void main(String[] args){
Maybe<String> maybe = Maybe.create(emitter -> {
emitter.onSuccess(DateUtil.getNowDate());
// emitter.onComplete();
});
maybe.subscribe(
data -> Logger.log(LogType.ON_SUCCESS, "# 현재 날짜시각: " + data),
error -> Logger.log(LogType.ON_ERROR, error),
() -> Logger.log(LogType.ON_COMPLETE)
);
}
}

View File

@@ -1,40 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleEmitter;
import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.core.SingleOnSubscribe;
import io.reactivex.rxjava3.disposables.Disposable;
import org.example.utils.DateUtil;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class SingleCreateEx {
public static void main(String[] args) {
Single<String> single = Single.create(new SingleOnSubscribe<String>() {
@Override
public void subscribe(@NonNull SingleEmitter<String> emitter) throws Throwable {
emitter.onSuccess(DateUtil.getNowDate());
}
});
single.subscribe(new SingleObserver<String>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onSuccess(@NonNull String s) {
Logger.log(LogType.ON_SUCCESS, "# 날짜시간: " + s);
}
@Override
public void onError(@NonNull Throwable e) {
Logger.log(LogType.ON_ERROR, e);
}
});
}
}

View File

@@ -1,18 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.core.Single;
import org.example.utils.DateUtil;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class SingleCreateLambdaEx {
public static void main(String[] args) {
Single<String> single = Single.create(emitter -> emitter.onSuccess(DateUtil.getNowDate()));
single.subscribe(
data -> Logger.log(LogType.ON_SUCCESS, "# 날짜시간: " + data),
error -> Logger.log(LogType.ON_ERROR, error)
);
}
}

View File

@@ -1,17 +0,0 @@
package org.example.ex05;
import io.reactivex.rxjava3.core.Single;
import org.example.utils.DateUtil;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class SingleJustEx {
public static void main(String[] args) {
Single.just(DateUtil.getNowDate())
.subscribe(
data -> Logger.log(LogType.ON_SUCCESS, "# 날짜시간: " + data),
error -> Logger.log(LogType.ON_ERROR, error)
);
}
}

View File

@@ -1,20 +0,0 @@
package org.example.ex06;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
/**
* 함수 디스크립터의 Consumer 예제
*/
public class FunctionalDescriptorConsumer {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 6, 10, 30, 65, 70, 102);
forEachPrint(numbers, n -> System.out.println(n));
}
public static <T> void forEachPrint(List<T> numbers, Consumer<T> c) {
for(T number : numbers)
c.accept(number);
}
}

View File

@@ -1,26 +0,0 @@
package org.example.ex06;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
/**
* 함수 디스크립터의 Function 예제
*/
public class FunctionalDescriptorFunction {
public static void main(String[] args) {
List<Character> characterList = Arrays.asList('a', 'b', 'c', 'd', 'e');
List<Integer> asciiNumbers = map(characterList, character -> (int) character);
for(int asciiNumber : asciiNumbers)
System.out.println(asciiNumber);
}
public static <T, R> List<R> map(List<T> list, Function<T, R> f){
List<R> result = new ArrayList<>();
for(T t : list)
result.add(f.apply(t));
return result;
}
}

View File

@@ -1,28 +0,0 @@
package org.example.ex06;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/**
* 함수 디스크립터의 Predicate 예제
*/
public class FunctionalDescriptorPredicate {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 6, 10, 30, 65, 70, 102);
List<Integer> result = filter(numbers, n -> n > 30);
for(int number : result)
System.out.println(number);
}
private static <T> List<T> filter(List<T> numbers, Predicate<T> p){
List<T> result = new ArrayList<>();
for(T number : numbers)
if(p.test(number))
result.add(number);
return result;
}
}

View File

@@ -1,40 +0,0 @@
package org.example.ex06;
import org.example.common.*;
import java.util.Arrays;
import java.util.List;
/**
* 사용자 정의 Predicate를 익명 클래스로 구현하는 예제
*/
public class FunctionalInterfaceEx {
public static void main(String[] args) {
List<Car> cars = Arrays.asList(
new Car(CarMaker.HYUNDAE, CarType.SUV, "팰리세이드", 28000000, true),
new Car(CarMaker.SAMSUNG, CarType.SEDAN, "SM5", 35000000, true),
new Car(CarMaker.CHEVROLET, CarType.SUV, "트래버스", 50000000, true),
new Car(CarMaker.KIA, CarType.SEDAN, "K5", 20000000, false),
new Car(CarMaker.SSANGYOUNG, CarType.SUV, "티볼리", 23000000, true)
);
List<Car> carsFilteredByPrice = CarFilter.filterCarByCustomPredicate(cars, new CarPredicate() {
@Override
public boolean test(Car car) {
return car.getCarPrice() > 30000000;
}
});
for(Car car : carsFilteredByPrice)
System.out.println("차 이름: " + car.getCarName() + ", 가격: " + car.getCarPrice());
List<Car> carsFilteredByCarType = CarFilter.filterCarByCustomPredicate(cars, new CarPredicate() {
@Override
public boolean test(Car car) {
return car.getCarType().equals(CarType.SUV);
}
});
for(Car car : carsFilteredByCarType)
System.out.println("차 이름: " + car.getCarName() + ", 차종: " + car.getCarType());
}
}

View File

@@ -1,34 +0,0 @@
package org.example.ex06;
import org.example.common.Car;
import org.example.common.CarFilter;
import org.example.common.CarMaker;
import org.example.common.CarType;
import java.util.Arrays;
import java.util.List;
/**
* 사용자 정의 Predicate를 람다 표현식으로 사용하는 예제
*/
public class FunctionalInterfaceToLamdaEx {
public static void main(String[] args) {
List<Car> cars = Arrays.asList(
new Car(CarMaker.HYUNDAE, CarType.SUV, "팰리세이드", 28000000, true),
new Car(CarMaker.SAMSUNG, CarType.SEDAN, "SM5", 35000000, true),
new Car(CarMaker.CHEVROLET, CarType.SUV, "트래버스", 50000000, true),
new Car(CarMaker.KIA, CarType.SEDAN, "K5", 20000000, false),
new Car(CarMaker.SSANGYOUNG, CarType.SUV, "티볼리", 23000000, true)
);
List<Car> carsFilteredByPrice =
CarFilter.filterCarByCustomPredicate(cars, (Car car) -> car.getCarPrice() > 30000000);
for(Car car : carsFilteredByPrice)
System.out.println("차 이름: " + car.getCarName() + ", 가격: " + car.getCarPrice());
List<Car> carsFilteredByCarType =
CarFilter.filterCarByCustomPredicate(cars, car -> car.getCarType().equals(CarType.SUV));
for(Car car : carsFilteredByCarType)
System.out.println("차 이름: " + car.getCarName() + ", 차종: " + car.getCarType());
}
}

View File

@@ -1,35 +0,0 @@
package org.example.ex06;
import org.example.common.Car;
import org.example.common.CarMaker;
import org.example.common.CarType;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* 하나의 추상 메서드를 가지고 있는 기존 인터페이스를 구현하는 예제
*/
public class LegacyInterfaceEx {
public static void main(String[] args) {
List<Car> cars = Arrays.asList(
new Car(CarMaker.HYUNDAE, CarType.SUV, "팰리세이드", 28000000, true),
new Car(CarMaker.SAMSUNG, CarType.SEDAN, "SM5", 35000000, true),
new Car(CarMaker.CHEVROLET, CarType.SUV, "트래버스", 50000000, true),
new Car(CarMaker.KIA, CarType.SEDAN, "K5", 20000000, false),
new Car(CarMaker.SSANGYOUNG, CarType.SUV, "티볼리", 23000000, true)
);
Collections.sort(cars, new Comparator<Car>() {
@Override
public int compare(Car car1, Car car2) {
return car1.getCarPrice() - car2.getCarPrice();
}
});
for(Car car : cars)
System.out.println("차 이름: " + car.getCarName() + ", 가격: " + car.getCarPrice());
}
}

View File

@@ -1,30 +0,0 @@
package org.example.ex06;
import org.example.common.Car;
import org.example.common.CarMaker;
import org.example.common.CarType;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 하나의 추상 메서드를 가지고 있는 기존 인터페이스를 함수형 인터페이스로 사용하는 예제
*/
public class LegacyInterfaceToFunctionalInterfaceEx {
public static void main(String[] args) {
List<Car> cars = Arrays.asList(
new Car(CarMaker.HYUNDAE, CarType.SUV, "팰리세이드", 28000000, true),
new Car(CarMaker.SAMSUNG, CarType.SEDAN, "SM5", 35000000, true),
new Car(CarMaker.CHEVROLET, CarType.SUV, "트래버스", 50000000, true),
new Car(CarMaker.KIA, CarType.SEDAN, "K5", 20000000, false),
new Car(CarMaker.SSANGYOUNG, CarType.SUV, "티볼리", 23000000, true)
);
Collections.sort(cars, (car1, car2) -> car1.getCarPrice() - car2.getCarPrice());
for(Car car : cars)
System.out.println("차 이름: " + car.getCarName() + ", 가격: " + car.getCarPrice());
}
}

View File

@@ -1,14 +0,0 @@
package org.example.ex07;
public class CarInventory {
private int incomingCount;
private int totalCount;
public CarInventory(int totalCount) {
this.totalCount = totalCount;
}
public int getExpectedTotalCount(int incomingCount){
return totalCount + incomingCount;
}
}

View File

@@ -1,20 +0,0 @@
package org.example.ex07;
import org.example.common.Car;
import java.util.function.Function;
/**
* Class Name::instance method 메서드 레퍼런스 예
*/
public class ClassNameInstanceMethodEx {
public static void main(String[] args) {
Function<Car, String> f1 = car -> car.getCarName();
String carName1 = f1.apply(new Car("트래버스"));
System.out.println(carName1);
Function<Car, String> f2 = Car::getCarName;
String carName2 = f2.apply(new Car("팰리세이드"));
System.out.println(carName2);
}
}

View File

@@ -1,26 +0,0 @@
package org.example.ex07;
import java.util.function.Function;
/**
* Class Name::static method 메서드 레퍼런스 예
*/
public class ClassNameStaticMethodEx {
public static void main(String[] args) {
// 람다 표현식 메서드 레퍼런스로 축약 전
Function<String, Integer> f1 = (String s) -> Integer.parseInt(s);
Integer result1 = f1.apply("3");
System.out.println(result1);
// 람다 표현식 메서드 레퍼런스로 축약 전
Function<String, Integer> f2 = s -> Integer.parseInt(s);
Integer result2 = f2.apply("3");
System.out.println(result2);
// 람다 표현식을 메서드 레퍼런스로 축약
Function<String, Integer> f3 = Integer::parseInt;
Integer result3 = f3.apply("3");
System.out.println(result3);
}
}

View File

@@ -1,20 +0,0 @@
package org.example.ex07;
import org.example.common.Car;
import java.util.function.Function;
/**
* Constructor::new 예
*/
public class ConstructorReferenceEx {
public static void main(String[] args) {
Function<String, Car> f1 = s -> new Car(s);
Car car1 = f1.apply("콜로라도");
System.out.println(car1.getCarName());
Function<String, Car> f2 = Car::new;
Car car2 = f2.apply("카니발");
System.out.println(car2.getCarName());
}
}

View File

@@ -1,32 +0,0 @@
package org.example.ex07;
import java.util.function.Function;
import java.util.function.IntUnaryOperator;
import java.util.function.UnaryOperator;
/**
* Object::instance method 예
*/
public class ObjectInstanceMethodExample {
public static void main(String[] args) {
final CarInventory carInventory = new CarInventory(10);
Function<Integer, Integer> f1 = count -> carInventory.getExpectedTotalCount(count);
int totalCount1 = f1.apply(10);
System.out.println(totalCount1);
Function<Integer, Integer> f2 = carInventory::getExpectedTotalCount;
int totalCount2 = f2.apply(20);
System.out.println(totalCount2);
// T -> T
UnaryOperator<Integer> f3 = carInventory::getExpectedTotalCount;
int totalCount3 = f3.apply(30);
System.out.println(totalCount3);
// Integer -> Integer
IntUnaryOperator f4 = carInventory::getExpectedTotalCount;
int totalCount4 = f4.applyAsInt(40);
System.out.println(totalCount4);
}
}

View File

@@ -1,31 +0,0 @@
package org.example.ex08;
import org.example.utils.LogType;
import org.example.utils.Logger;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
public class CarRepairShop {
public int getCarRepairCostSync(int brokens) {
return calculateCarRepair(brokens);
}
public Future<Integer> getCarRepairCostAsync(int brokens) {
return CompletableFuture.supplyAsync(() -> calculateCarRepair(brokens));
}
private int calculateCarRepair(int brokens){
Logger.log(LogType.PRINT, "# 차량 수리비 계산 중................");
delay();
return brokens * 20000;
}
private void delay(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View File

@@ -1,56 +0,0 @@
package org.example.ex08;
import org.example.utils.LogType;
import org.example.utils.Logger;
import java.util.concurrent.Future;
public class FutureExampleASync {
public static void main(String[] args){
long startTime = System.currentTimeMillis();
Logger.log(LogType.PRINT, "# Start");
CarRepairShop shop = new CarRepairShop();
// 차량 수리비(시간이 더 오래 걸리는 미래에 끝날 일)
Future<Integer> future = shop.getCarRepairCostAsync(10);
// 회사에 병가 신청(짧은 처리 시간)
requestSickLeave("20170903-01");
// 보험 청구(짧은 처리 시간)
requestInsurance("44나4444");
try {
int carRepairCost = future.get();
Logger.log(LogType.PRINT, "# (1) 차량 수리비 계산이 완료되었습니다.");
Logger.log(LogType.PRINT, "# 차량 수리비는 " + carRepairCost + "원 입니다.");
} catch (Exception e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
double executeTime = (endTime - startTime) / 1000.0;
System.out.println();
System.out.println("# 처리 시간: " + executeTime);
}
private static void requestSickLeave(String empNumber) {
try {
Thread.sleep(1000);
Logger.log(LogType.PRINT, "# (2) 병가 신청이 완료되었습니다.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void requestInsurance(String carNumber) {
try {
Thread.sleep(1000);
Logger.log(LogType.PRINT, "# (3) 보험 접수가 완료 되었습니다.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View File

@@ -1,50 +0,0 @@
package org.example.ex08;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class FutureExampleSync {
public static void main(String[] args){
long startTime = System.currentTimeMillis();
CarRepairShop shop = new CarRepairShop();
// 차량 수리비
int carRepairCost = shop.getCarRepairCostSync(10);
Logger.log(LogType.PRINT, "# (1) 차량 수리비 계산이 완료되었습니다.");
Logger.log(LogType.PRINT, "# 차량 수리비는 " + carRepairCost + "원 입니다.");
// 회사에 병가 신청
requestSickLeave("20170903-01");
// 보험 접수
requestInsurance("44나4444");
long endTime = System.currentTimeMillis();
double executeTime = (endTime - startTime) / 1000.0;
System.out.println();
System.out.println("# 처리 시간: " + executeTime + "");
}
private static void requestSickLeave(String empNumber) {
try {
Thread.sleep(1000);
Logger.log(LogType.PRINT, "# (2) 병가 신청이 완료되었습니다.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void requestInsurance(String carNumber) {
try {
Thread.sleep(1000);
Logger.log(LogType.PRINT, "# (3) 보험 접수가 완료 되었습니다.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

View File

@@ -1,30 +0,0 @@
package org.example.ex08;
import io.reactivex.rxjava3.core.Observable;
import org.example.utils.LogType;
import org.example.utils.Logger;
import java.time.LocalTime;
/**
* 실제 구독이 발생할 때 Observable을 새로 반환하여 새로운 Observable을 생성한다.
* defer()를 활용하면 데이터 흐름의 생성을 지연하는 효과를 보여준다.
*/
public class ObservableDeferEx {
public static void main(String[] args) throws InterruptedException {
Observable<LocalTime> observable = Observable.defer(() -> {
LocalTime currentTime = LocalTime.now();
return Observable.just(currentTime);
});
Observable<LocalTime> observableJust = Observable.just(LocalTime.now());
observable.subscribe(time -> Logger.log(LogType.PRINT, " # defer() 구독1의 구독 시간: " + time));
observableJust.subscribe(time -> Logger.log(LogType.PRINT, " # just() 구독1의 구독 시간: " + time));
Thread.sleep(3000);
observable.subscribe(time -> Logger.log(LogType.PRINT, " # defer() 구독2의 구독 시간: " + time));
observableJust.subscribe(time -> Logger.log(LogType.PRINT, " # just() 구독자2의 구독 시간: " + time));
}
}

View File

@@ -1,44 +0,0 @@
package org.example.ex08;
import io.reactivex.rxjava3.core.Observable;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class ObservableFromFutureEx {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Logger.log(LogType.PRINT, "# start time");
// 긴 처리 시간이 걸리는 작업
Future<Double> future = longTimeWork();
// 짧은 처리 시간이 걸리는 작업
shortTimeWork();
Observable.fromFuture(future)
.subscribe(data -> Logger.log(LogType.PRINT, "# 긴 처리 시간 작업 결과 : " + data));
Logger.log(LogType.PRINT, "# end time");
}
public static CompletableFuture<Double> longTimeWork(){
return CompletableFuture.supplyAsync(ObservableFromFutureEx::calculate);
}
private static Double calculate() {
Logger.log(LogType.PRINT, "# 긴 처리 시간이 걸리는 작업 중.........");
TimeUtil.sleep(6000L);
return 100000000000000000.0;
}
private static void shortTimeWork() {
TimeUtil.sleep(3000L);
Logger.log(LogType.PRINT, "# 짧은 처리 시간 작업 완료!");
}
}

View File

@@ -1,17 +0,0 @@
package org.example.ex08;
import io.reactivex.rxjava3.core.Observable;
import org.example.utils.LogType;
import org.example.utils.Logger;
import java.util.Arrays;
import java.util.List;
public class ObservableFromIterableEx {
public static void main(String[] args){
List<String> countries = Arrays.asList("Korea", "Canada", "USA", "Italy");
Observable.fromIterable(countries)
.subscribe(country -> Logger.log(LogType.ON_NEXT, country));
}
}

View File

@@ -1,23 +0,0 @@
package org.example.ex08;
import io.reactivex.rxjava3.core.Observable;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
import java.util.concurrent.TimeUnit;
/**
* polling 용도로 주로 사용.
*/
public class ObservableIntervalEx {
public static void main(String[] args){
System.out.println("# start : " + TimeUtil.getCurrentTimeFormatted());
Observable.interval(0, 1000L, TimeUnit.MILLISECONDS)
.map(num -> num + " count")
.subscribe(data -> Logger.log(LogType.ON_NEXT, data));
TimeUtil.sleep(3000);
}
}

View File

@@ -1,15 +0,0 @@
package org.example.ex08;
import io.reactivex.rxjava3.core.Observable;
import org.example.utils.LogType;
import org.example.utils.Logger;
/**
* 반복문으로 사용 가능
*/
public class ObservableRangeEx {
public static void main(String[] args){
Observable<Integer> source = Observable.range(0, 5);
source.subscribe(num -> Logger.log(LogType.ON_NEXT, num));
}
}

View File

@@ -1,24 +0,0 @@
package org.example.ex08;
import io.reactivex.rxjava3.core.Observable;
import org.example.utils.LogType;
import org.example.utils.Logger;
import org.example.utils.TimeUtil;
import java.util.concurrent.TimeUnit;
/**
* 설정한 시간이 지난 후에 특정 동작을 수행하고자 할때 사용
*/
public class ObservableTimerEx {
public static void main(String[] args){
Logger.log(LogType.PRINT, "# Start!");
Observable<String> observable =
Observable.timer(2000, TimeUnit.MILLISECONDS)
.map(count -> "Do work!");
observable.subscribe(data -> Logger.log(LogType.ON_NEXT, data));
TimeUtil.sleep(3000);
}
}

View File

@@ -1,18 +0,0 @@
package org.example.ex09;
import io.reactivex.rxjava3.core.Observable;
import org.example.common.SampleData;
import org.example.utils.LogType;
import org.example.utils.Logger;
/**
* 이미 통지한 데이터와 같은 데이터는 제외하고 통지
* 유일한 값을 처리하고자 할때 사용
*/
public class ObservableDistinctEx01 {
public static void main(String[] args) {
Observable.fromArray(SampleData.carMakersDuplicated)
.distinct()
.subscribe(carMaker -> Logger.log(LogType.ON_NEXT, carMaker));
}
}

View File

@@ -1,16 +0,0 @@
package org.example.ex09;
import io.reactivex.rxjava3.core.Observable;
import org.example.common.CarMaker;
import org.example.common.SampleData;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class ObservableDistinctEx02 {
public static void main(String[] args) {
Observable.fromArray(SampleData.carMakersDuplicated)
.distinct()
.filter(carMaker -> carMaker == CarMaker.SSANGYOUNG)
.subscribe(carMaker -> Logger.log(LogType.ON_NEXT, carMaker));
}
}

View File

@@ -1,19 +0,0 @@
package org.example.ex09;
import io.reactivex.rxjava3.core.Observable;
import org.example.common.Car;
import org.example.common.SampleData;
import org.example.utils.LogType;
import org.example.utils.Logger;
/**
* 객체의 특정 필드를 기준으로 distinct 하는 예제
*/
public class ObservableDistinctEx03 {
public static void main(String[] args) {
Observable.fromIterable(SampleData.carList)
.distinct(Car::getCarMaker)
.subscribe(car -> Logger.log(LogType.ON_NEXT, car.getCarName()));
}
}

View File

@@ -1,15 +0,0 @@
package org.example.ex09;
import io.reactivex.rxjava3.core.Observable;
import org.example.common.CarMaker;
import org.example.common.SampleData;
import org.example.utils.LogType;
import org.example.utils.Logger;
public class ObservableFilterEx01 {
public static void main(String[] args) {
Observable.fromIterable(SampleData.carList)
.filter(car -> car.getCarMaker() == CarMaker.CHEVROLET)
.subscribe(car -> Logger.log(LogType.ON_NEXT, car.getCarMaker() + " : " + car.getCarName()));
}
}

View File

@@ -1,14 +0,0 @@
package org.example.ex09;
import io.reactivex.rxjava3.core.Observable;
import org.example.common.CarMaker;
import org.example.common.SampleData;
public class ObservableFilterEx02 {
public static void main(String[] args) {
Observable.fromIterable(SampleData.carList)
.filter(car -> car.getCarMaker() == CarMaker.CHEVROLET)
.filter(car -> car.getCarPrice() > 30000000)
.subscribe(car -> System.out.println(car.getCarName()));
}
}

Some files were not shown because too many files have changed in this diff Show More