Advertisement
Guest User

Untitled

a guest
Feb 14th, 2025
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.88 KB | None | 0 0
  1. class Test {
  2.     private val refreshTrigger: MutableSharedFlow<Unit> = MutableSharedFlow(extraBufferCapacity = 1)
  3.  
  4.     // This is my entry point called from a ViewModel with the `viewModelScope`
  5.     fun launchIn(scope: CoroutineScope) {
  6.         val test = Test()
  7.         test()
  8.             .onEach { log("Got: $it") }
  9.             .launchIn(scope)
  10.         scope.launch {
  11.             delay(2000L)
  12.             test.refresh()
  13.         }
  14.     }
  15.  
  16.     @OptIn(ExperimentalCoroutinesApi::class)
  17.     operator fun invoke(): Flow<Any> = refreshTrigger
  18.         .onStart { emit(Unit) }
  19.         .onEach { log("1 refreshing flow!") }
  20.         .flatMapLatest {
  21.             log("2 remitting flow!")
  22.             randomFlow()
  23.         }
  24.  
  25.     private fun randomFlow(): Flow<Any> = flow { emit(Any()) }
  26.  
  27.     fun refresh() {
  28.         log("Emit refresh")
  29.         refreshTrigger.tryEmit(Unit)
  30.     }
  31.  
  32.     private fun log(message: String) {
  33.         AppLogger.i(message, "kotlinlang")
  34.     }
  35. }
  36.  
  37. /*
  38.  * Android output:
  39. 16:16:02.812 kotlinlang               I  1 refreshing flow!
  40. 16:16:02.813 kotlinlang               I  2 remitting flow!
  41. 16:16:02.814 kotlinlang               I  Got: java.lang.Object@3df904f
  42. 16:16:04.816 kotlinlang               I  Emit refresh
  43. 16:16:04.816 kotlinlang               I  1 refreshing flow!
  44. 16:16:04.817 kotlinlang               I  2 remitting flow!
  45. 16:16:04.817 kotlinlang               I  Got: java.lang.Object@b915e29
  46.  */
  47.  
  48. /*
  49.  * iOS output:
  50. 02-14 16:17:20.205 💙 INFO kotlinlang - 1 refreshing flow!
  51. 02-14 16:17:20.206 💙 INFO kotlinlang - 2 remitting flow!
  52. 02-14 16:17:20.206 💙 INFO kotlinlang - Got: kotlin.Any@2ea16c8
  53. 02-14 16:17:22.207 💙 INFO kotlinlang - Emit refresh
  54. 02-14 16:17:22.207 💙 INFO kotlinlang - 1 refreshing flow!
  55. 02-14 16:17:22.208 💙 INFO kotlinlang - 2 remitting flow!
  56. 02-14 16:17:22.208 💙 INFO kotlinlang - Got: kotlin.Any@2ea1f98
  57. */
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement