我开始使用Koin将DI引入Android。我遵循了MVP教程,并且将其用于一个Activity。
我尝试从Fragment中删除演示者,然后该应用程序运行完全没有问题。它可以毫无问题地用于我的主要活动,这是我最困惑的事情。
val appModule = module {
single { Room.databaseBuilder(get(), AppDatabase::class.java, "items_database").build() }
single { get<AppDatabase>().itemsDAO() }
single<ItemRepositoryInterface> {
ItemRepository(
get()
)
}
single <ItemInteractorInterface> {
ItemInteractor(
get()
)
}
viewModel { ItemPresenter(get()) }
}
interface ItemRepositoryInterface {
fun getAll(): Observable<List<Item>>
fun insert(item: Item)
fun deleteAll()
fun updateItem(item: Item)
fun delete(item: Item)
}
class ItemRepository(private val itemsDao: ItemDAO) : ItemRepositoryInterface {
override fun getAll(): Observable<List<Item>> {
return itemsDao.getAll()
}
override fun insert(itemData: Item) {
Single.fromCallable {
itemsDao.insert(item)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({}, {
})
}
override fun deleteAll() {
itemsDao.deleteAll()
}
override fun updateItem(itemData: Item) {
itemsDao.updateItem(itemData)
}
override fun delete(itemData: Item) {
itemsDao.delete(itemData)
}
}
interface ItemInteractorInterface {
fun insert(item: Item)
fun update(item: Item)
fun delete(item: Item)
fun deleteAllItems()
fun getAllItems(): Observable<List<Item>>
}
class ItemInteractor(private val itemRepository: ItemInteractorInterface) :
ItemInteractorInterface {
override fun insert(item: Item) {
itemRepository.insert(item)
}
override fun update(item: Item) {
itemRepository.update(item)
}
override fun delete(item: Item) {
itemRepository.delete(item)
}
override fun deleteAllItems() {
itemRepository.deleteAllItems()
}
override fun getAllItems(): Observable<List<Item>> {
return itemRepository.getAllItems()
}
}
class MainFragment : Fragment() {
private val itemPresenter: ItemPresenter by sharedViewModel<ItemPresenter>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_main, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
itemPresenter.getAllItems().observe(this, Observer { items ->
recyclerView.adapter = PListAdapter(items.reversed())
})
}
}
它在此行崩溃: itemPresenter.getAllItems() 我得到的错误是java.lang.StackOverflowError:堆栈大小8MB 然后是这个巨大的错误。
跟随它指向的跟踪
single <ItemInteractorInterface> {