Skip to content

Commit

Permalink
Use typeOf as key instead of KClass in InstanceKeeper#getStore
Browse files Browse the repository at this point in the history
  • Loading branch information
arkivanov committed May 27, 2024
1 parent 9721595 commit c3a2df0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package com.arkivanov.mvikotlin.core.instancekeeper
import com.arkivanov.essenty.instancekeeper.InstanceKeeper
import com.arkivanov.essenty.instancekeeper.getOrCreate
import com.arkivanov.mvikotlin.core.store.Store
import kotlin.reflect.typeOf

fun <T : Store<*, *, *>> InstanceKeeper.getStore(key: Any, factory: () -> T): T =
getOrCreate(key = key) {
StoreInstance(factory())
}.store

inline fun <reified T : Store<*, *, *>> InstanceKeeper.getStore(noinline factory: () -> T): T =
getStore(key = T::class, factory = factory)
getStore(key = typeOf<T>(), factory = factory)

private class StoreInstance<out T : Store<*, *, *>>(
val store: T
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.arkivanov.mvikotlin.core.instancekeeper

import com.arkivanov.essenty.instancekeeper.InstanceKeeperDispatcher
import com.arkivanov.mvikotlin.core.rx.Disposable
import com.arkivanov.mvikotlin.core.rx.Observer
import com.arkivanov.mvikotlin.core.store.Store
import kotlin.test.Test
import kotlin.test.assertNotSame
import kotlin.test.assertSame

@Suppress("TestFunctionName")
class InstanceKeeperExtTest {

private val keeper = InstanceKeeperDispatcher()

@Test
fun WHEN_getStore_with_same_type_THEN_same_instance() {
val store1 = keeper.getStore { store<String, Float, Int>() }
val store2 = keeper.getStore { store<String, Float, Int>() }

assertSame(store1, store2)
}

@Test
fun WHEN_getStore_with_different_types_THEN_instances_not_same() {
val store1 = keeper.getStore { store<Int, String, Float>() }
val store2 = keeper.getStore { store<String, Float, Int>() }

assertNotSame<Store<*, *, *>>(store1, store2)
}

private fun <Intent : Any, State : Any, Label : Any> store(): Store<Intent, State, Label> =
object : Store<Intent, State, Label> {
override val state: State get() = error("Not implemented")
override val isDisposed: Boolean get() = error("Not implemented")

override fun states(observer: Observer<State>): Disposable =
error("Not implemented")

override fun labels(observer: Observer<Label>): Disposable =
error("Not implemented")

override fun accept(intent: Intent) {
error("Not implemented")
}

override fun init() {
error("Not implemented")
}

override fun dispose() {
error("Not implemented")
}
}
}

0 comments on commit c3a2df0

Please sign in to comment.