为什么我的Singleton已同步但创建了很多次?

时间:2018-07-02 06:24:40

标签: java android kotlin android-intentservice android-livedata

由于某种原因,我的单例存储库是通过后台线程多次创建的,但是同步应该有所帮助。有人可以帮忙吗?如果需要,我将提供代码片段和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();
}

1 个答案:

答案 0 :(得分:6)

您永远不会分配INSTANCE

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

    return INSTANCE;
}