Skip to content

Commit

Permalink
Merge pull request #2 from GSM-MSG/feature/1_change_logic_to_observe_…
Browse files Browse the repository at this point in the history
…local

🔀 :: (#1) - change logic to observe local
  • Loading branch information
leehyeonbin authored Apr 30, 2023
2 parents a20e67a + ebcbf44 commit 6e6f991
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/kotlin/Macaroni.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ class Macaroni<T>(
onRemoteObservable: suspend () -> Flow<T>,
getLocalData: suspend () -> T,
onUpdateLocal: suspend (T) -> Unit,
onRemoteFailure: (Throwable) -> Unit
onRemoteFailure: (Throwable) -> Unit = {}
) {
// remote
// 'onRemoteObservable' should pass the logic
Expand Down
47 changes: 47 additions & 0 deletions src/main/kotlin/MacaroniFlow.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.first

class MacaroniFlow<T> constructor(
onRemoteObservable: suspend () -> Flow<T>,
onUpdateLocal: suspend (T) -> Unit,
onLocalObservable: suspend () -> Flow<T>,
) {

private var onRemoteObservable: suspend () -> Flow<T>
private var onUpdateLocal: suspend (T) -> Unit
private var onLocalObservable: suspend () -> Flow<T>

init {
this.onRemoteObservable = onRemoteObservable
this.onUpdateLocal = onUpdateLocal
this.onLocalObservable = onLocalObservable
}

suspend fun fetch(onNext: (MacaroniStatus, T) -> Unit) {
val localData = onLocalObservable().first()
onLocalObservable()
.drop(1)
.collect { data ->
onNext(Success, data)
}
try {
runCatching {
onNext(Loading, localData)
onRemoteObservable()
}.onSuccess {
it.collect { data ->
if (localData != data) {
onUpdateLocal(data)
} else {
onNext(Success, data)
}
}
}.onFailure {
onNext(Error, localData)
}
} catch (e: Exception) {
onNext(Error, localData)
}
}
}
28 changes: 28 additions & 0 deletions src/test/kotlin/MacaroniFlowTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow

private suspend fun main() {
val macaroni = MacaroniFlow(
onRemoteObservable = {
flow {
delay(100)
emit(TestStatus("onRemoteObservable", "test"))
}
},
onUpdateLocal = {
delay(100)
println("onUpdateLocal")
},
onLocalObservable = {
flow {
emit(TestStatus("getLocalData", "first"))
delay(200)
emit(TestStatus("changeLocal", "nice"))
}
}
)

macaroni.fetch { status, result ->
println("status: $status, result: $result")
}
}

0 comments on commit 6e6f991

Please sign in to comment.