java - 为什么我的单例是同步的,但它被创建了很多次?

标签 java android kotlin android-intentservice android-livedata

由于某种原因,我的单例存储库从后台线程创建了很多次,但同步应该有所帮助。有人可以帮忙吗?如果需要的话我会提供代码 fragment 和github链接。

我的 IntentService 类:

  @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d(MainActivity.TAG, "ArticleIntentService - onHandleIntent");


        LiveData<List<Article>> liveArticles = ArticleRepository.getInstance(getApplication())
                .loadFromNetwork(PAGE_NUMBER, PAGE_SIZE);
        PAGE_NUMBER++;
        liveArticles.observeForever(articles -> {
            Log.d(MainActivity.TAG, "onStartJob - onChanged!!!!!!");
//                liveArticles.removeObserver(this);
            NotificationUtils.showNotification(context, articles.get(0).getSectionName(), articles.get(0).getWebTitle());

        });

    }

我的存储库:

public static ArticleRepository INSTANCE;

public static synchronized ArticleRepository getInstance(Application application){
    if(INSTANCE == null){
        Log.d(TAG, "ArticleRepository getInstance is NULL");
        return  new ArticleRepository(application);
    }

    return INSTANCE;
}

private ArticleRepository(Application application) {
    Log.d(TAG, "ArticleRepository constructor");
    mContext = application;
    mArticles = new MutableLiveData<>();
    ArticleRoomDatabase db = ArticleRoomDatabase.getInstance(application);
    mArticleDao = db.articleDao();
}

最佳答案

您从未分配INSTANCE:

public static synchronized ArticleRepository getInstance(Application application){
    if(INSTANCE == null){
        Log.d(TAG, "ArticleRepository getInstance is NULL");
        INSTANCE = new ArticleRepository(application);
    }

    return INSTANCE;
}

关于java - 为什么我的单例是同步的,但它被创建了很多次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51130152/

相关文章:

java - 如何使用 HashMap 解读单词列表?

java - 使用 java 将项目存储到 DynamoDB 时发生 ConditionalCheckFailed 异常

android - 我可以使用 android NDK 修改之前创建的 .so 文件吗?

java - Android 处理程序和线程在启动时未运行?

kotlin - 如何弥合Netty ChannelInboundHandler与kotlinx协程调度程序之间的差距?

java - Groovy、Scala 可能让我的生活更轻松?

java - 用户通过Android中的任何第三方应用程序(CC Cleaner或Kill应用程序)清理应用程序后是否可以重新启动后台服务?

java - 我对 abiFilters 配置有疑问

numbers - 如何在 Kotlin 中将 Int 转换为十六进制字符串?

java - 如何对表列求和并将总值设置为文本字段?