diff --git a/.gradle/7.1/executionHistory/executionHistory.bin b/.gradle/7.1/executionHistory/executionHistory.bin
index e246eea..11c64f4 100644
Binary files a/.gradle/7.1/executionHistory/executionHistory.bin and b/.gradle/7.1/executionHistory/executionHistory.bin differ
diff --git a/.gradle/7.1/executionHistory/executionHistory.lock b/.gradle/7.1/executionHistory/executionHistory.lock
index c4f0e4a..21c2eab 100644
Binary files a/.gradle/7.1/executionHistory/executionHistory.lock and b/.gradle/7.1/executionHistory/executionHistory.lock differ
diff --git a/.gradle/7.1/fileHashes/fileHashes.bin b/.gradle/7.1/fileHashes/fileHashes.bin
index 8f6ab44..7565164 100644
Binary files a/.gradle/7.1/fileHashes/fileHashes.bin and b/.gradle/7.1/fileHashes/fileHashes.bin differ
diff --git a/.gradle/7.1/fileHashes/fileHashes.lock b/.gradle/7.1/fileHashes/fileHashes.lock
index 02e1216..5b1d44b 100644
Binary files a/.gradle/7.1/fileHashes/fileHashes.lock and b/.gradle/7.1/fileHashes/fileHashes.lock differ
diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock
index 25617e1..e8263cd 100644
Binary files a/.gradle/buildOutputCleanup/buildOutputCleanup.lock and b/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ
diff --git a/.gradle/buildOutputCleanup/outputFiles.bin b/.gradle/buildOutputCleanup/outputFiles.bin
index 177c456..ea5c2db 100644
Binary files a/.gradle/buildOutputCleanup/outputFiles.bin and b/.gradle/buildOutputCleanup/outputFiles.bin differ
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..35eb1dd
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt
index 18c0de6..b933ddd 100644
--- a/src/main/kotlin/Main.kt
+++ b/src/main/kotlin/Main.kt
@@ -1,8 +1,10 @@
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
+import io.reactivex.rxjava3.core.Single
import java.rmi.server.ServerNotActiveException
import java.util.*
+import java.util.concurrent.Callable
import java.util.concurrent.TimeUnit
import kotlin.random.Random
@@ -20,48 +22,152 @@ fun main() {
//
// Несмотря на то, что в некоторых заданиях фигурируют слова "синхронный" и "асинхронный" в рамках текущего ДЗ
// это всего лишь имитация, реальное переключение между потоками будет рассмотрено на следующем семинаре
+
+ println("Start Q1");
+
+ //Single.timer(1L,TimeUnit.MILLISECONDS).blockingSubscribe({println("0")},{println("error")});
+ //Some Emission
+ //Some Emission
+ //val singleSource = Maybe.just("single item");
+ /// maybe_array = Maybe.fromCallable ( {requestDataFromServerAsync();} );
+/*
+ val count = -1
+ require(count >= 0) { println("Count must be non-negative, was $count") }
+ require(requestServerAsync() !is Unit) { println("kuku") }
+ //println("require(requestServerAsync() is Unit)"+require(requestServerAsync() is Unit));
+*/
+ Maybe.fromCallable( {
+ // val arr: Array = arrayOfNulls(1);
+ //val arr: ByteArray? = arrayOfNulls(1)
+ // don't know standart fun like arrayOfNulls for List
+ // var result: MutableList = arr.toMutableList(); //arrayListOf(list.size);
+ var result: ByteArray? = requestDataFromServerAsync()
+ // val result: = "";
+ result
+ }).blockingSubscribe({s : ByteArray? -> println("Item received: from Maybe"+s.contentToString());
+ },
+ { obj: Throwable -> obj.printStackTrace() } ) { println("Done from MaybeSource") }
+
+
+
+ /* singleSource.subscribe(
+ { s: String -> println("Item received: from singleSource $s") },
+ { obj: Throwable -> obj.printStackTrace() }
+ ) { println("Done from SingleSource") }
+ */
+
+
+ // Maybe maybe_array = Maybe.just("single item");
+ // Maybe.blockingSubscribe({},{});
+ // Maybe.fromCallable ( requestDataFromServerAsync() )
+ println("Finished Q1");
+
+
+ println("Start Q2");
+ //requestServerAsync();
+ //assertTrue( is Unit);
+ /* val callable1 = object : Callable {
+ override fun call(): Int = 1
+ }
+ val c1 = createCallable(callable1)
+ println("callable1 = ${c1.call()}")
+
+ val callable2 = object : Callable {
+ override fun call(): Unit { println("Hello"); throw Exception("Hello") }
+ }
+ val c2 = createCallable(callable2)
+ c2.call()
+
+ */
+
+ Completable.fromCallable ( object: Callable {
+ override fun call(): Unit { requestServerAsync()}} ).
+ subscribe({println("Successful");},
+ { obj: Throwable -> obj.printStackTrace() } );
+ //.fromCallable(requestServerAsync())
+ //.timer(1L,TimeUnit.MILLISECONDS).blockingSubscribe({println("2")},{println("error2")});
+
+
+ println("Finished Q2");
+
+ println("Start Q3");
+ //val val1 = requestDataFromDbAsync();
+
+ /* Single.fromCallable ({
+ var result: Int? = requestDataFromDbAsync() }
+ ).onErrorComplete(println("eee"))
+*/
+ //onErrorComplete(result: Throwable -> println("--"))
+
+ /* blockingSubscribe({println("Successful");},
+ { obj: Throwable -> obj.printStackTrace() })
+
+ */
+
+
+/* ({s : Int? -> println("Item received: from Single:"+s.toString()})
+ { obj: Throwable -> obj.printStackTrace() })
+ */
+ println("Finish Q3");
+
+ println("Start Q4");
+ emitEachSecond();
+ println("Finish Q4");
+
+
+
+
}
// 1) Какой источник лучше всего подойдёт для запроса на сервер, который возвращает результат?
+// Maybe
// Почему?
+// Согласно лекции номер 2
// Дописать функцию
-fun requestDataFromServerAsync() /* -> ??? */ {
+fun requestDataFromServerAsync() : ByteArray? /* -> ??? */ {
// Функция имитирует синхронный запрос на сервер, возвращающий результат
fun getDataFromServerSync(): ByteArray? {
Thread.sleep(LATENCY);
val success = Random.nextBoolean()
- return if (success) Random.nextBytes(RESPONSE_LENGTH) else null
- }
+ //return if (success) Random.nextBytes(RESPONSE_LENGTH) else null
+ return Random.nextBytes(RESPONSE_LENGTH)
+ }
+ return getDataFromServerSync()
/* return ??? */
}
// 2) Какой источник лучше всего подойдёт для запроса на сервер, который НЕ возвращает результат?
+//Completable
// Почему?
+// По определению ..
// Дописать функцию
-fun requestServerAsync() /* -> ??? */ {
+fun requestServerAsync() :Unit /* -> ??? */ {
// Функция имитирует синхронный запрос на сервер, не возвращающий результат
fun getDataFromServerSync() {
Thread.sleep(LATENCY)
if (Random.nextBoolean()) throw ServerNotActiveException()
}
-
+ return getDataFromServerSync()
/* return ??? */
}
// 3) Какой источник лучше всего подойдёт для однократного асинхронного возвращения значения из базы данных?
+//Single
// Почему?
+//Single — реактивный Callable, потому что тут появляется возможность вернуть результат операции. Продолжая сравнение с Kotlin, можно сказать, что Single — это fun single(): T { }. Таким образом, чтобы подписаться на него, необходимо реализовать onSuccess(T) и onError.
+
// Дописать функцию
-fun requestDataFromDbAsync() /* -> ??? */ {
+fun requestDataFromDbAsync() : T? /* -> ??? */ {
// Функция имитирует синхронный запрос к БД не возвращающий результата
fun getDataFromDbSync(): T? {
Thread.sleep(LATENCY); return null
}
-
+ return getDataFromDbSync()
/* return */
}
@@ -76,7 +182,7 @@ fun emitEachSecond() {
// Принтер
fun printer(value: Long) = println("${Date()}: value = $value")
-
+ source().doOnEach { Thread.sleep(2000L)}.blockingSubscribe({printer(it)})
// code here
}